package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.ConditionConstant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchDataInConditionDTO;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.MenuTypeEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.enums.PatternEnum;
import com.xbongbong.paas.enums.clazz.ConditionClass;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.entity.OperateLogEntity;
import com.xbongbong.paas.log.model.OperateLogModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.pojo.dto.ConditionListDTO;
import com.xbongbong.paas.pojo.vo.ConditionListVO;
import com.xbongbong.paas.pojo.vo.SearchDataInConditionVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.ConditionService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.PackageService;
import com.xbongbong.paas.service.SmartSettingsService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.constant.AiAssistantConstant;
import com.xbongbong.pro.constant.DynamicManagerConstant;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.enums.CustomStrategyTypeEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.DynamicManagerLevelEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.WeekEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.ControlCenterMenuEnum;
import com.xbongbong.pro.enums.menu.enums.SystemAppMenuEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.smartsettings.enums.AiAssistantPushTypeEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartActionTypeEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartSettingsConditionEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartSettingsFieldEnum;
import com.xbongbong.pro.enums.smartsettings.enums.StrategyTypeEnum;
import com.xbongbong.pro.formexplain.pojo.ReturnExplainPojo;
import com.xbongbong.pro.log.pojo.DetailLogPojo;
import com.xbongbong.pro.menu.pojo.dto.MenuNewListDTO;
import com.xbongbong.pro.menu.pojo.vo.AppMenuListVO;
import com.xbongbong.pro.menu.pojo.vo.PaasAppMenuVO;
import com.xbongbong.pro.service.toolbox.smartsettings.help.SmartSettingsHelp;
import com.xbongbong.pro.smartsettings.pojo.AiTriggerConditionLogPojo;
import com.xbongbong.pro.smartsettings.pojo.SmartFieldAttrPojo;
import com.xbongbong.pro.smartsettings.pojo.SmartSettingsBusinessListPojo;
import com.xbongbong.pro.smartsettings.pojo.SmartSettingsListPojo;
import com.xbongbong.pro.smartsettings.pojo.SmartStrategyPojo;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsBusinessListDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsConditionValueDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsDelDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsEnableDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsGetDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsListDTO;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartSettingsSaveDTO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsBusinessListVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsConditionValueVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsDelVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsEnableVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsGetVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsListVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsMenuListVO;
import com.xbongbong.pro.smartsettings.pojo.vo.SmartSettingsSaveVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.SaleStageEntity;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.saas.help.MarketManagementBusinessHelp;
import com.xbongbong.saas.model.AiAssistantConfigModel;
import com.xbongbong.saas.model.AiAssistantModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.sys.enums.RoleEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @description: 智能助手
 * @Author: hongxiao
 * @date: 2019-04-23 21:26
 * @since v1.0
 */
@Service("smartSettingsService")
public class SmartSettingsServiceImpl implements SmartSettingsService {

    private static final Logger LOG = LoggerFactory.getLogger(SmartSettingsServiceImpl.class);


    /**
     * 默认智能助手个数
     * SAAS:11个（新增客户、无跟进客户、遗忘客户、客户生日、新增合同、
     * 合同即将到期、回款到期提醒、回款逾期提醒、机会阶段变更提醒、遗忘机会、周报）
     * PAAS:15个（新增供应商、无跟进供应商、遗忘供应商、新增采购合同、采购即将到货、
     * 付款到期提醒、付款逾期提醒、生产完成提醒、待采购未处理、待生产未处理、
     * 待入库未处理、待出库未处理、产品库存下限预警、产品库存上限预警、产品保质期预警）
     */

    @Resource
    private AiAssistantModel aiAssistantModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private OperateLogModel operateLogModel;
    @Resource
    private ConditionService conditionService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private AiAssistantConfigModel aiAssistantConfigModel;
    @Resource
    private SmartSettingsHelp smartSettingsHelp;
    @Resource
    private PackageService packageService;
    @Resource
    private LogHelp logHelp;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;

    @Override
    public SmartSettingsBusinessListVO businessList(SmartSettingsBusinessListDTO businessListDTO) throws XbbException {
        SmartSettingsBusinessListVO businessListVO = new SmartSettingsBusinessListVO();

        String corpid = businessListDTO.getCorpid();

        // 初始化默认智能助手
        initSmartSettingsForCrm(corpid);
        initSmartSettingsForJxc(corpid);

        // 智能助手列表
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        List<AiAssistantEntity> list = aiAssistantModel.findEntitys(param);
        if (CollectionsUtil.isEmpty(list)) {
            businessListVO.setList(new ArrayList<>());
            return businessListVO;
        }
        // 表单列表，paas菜单列表
        Set<Long> formIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> paasMenuIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        // {businessType: businessPojo}  {menuId: businessPojo}
        Map<Long, SmartSettingsBusinessListPojo> saasMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, SmartSettingsBusinessListPojo> paasMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        list.forEach(item -> {
            setBusinessListPojo(item, formIdSet, paasMenuIdSet, saasMap, paasMap);
        });

        // 获取表单数据
        param.clear();
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("idIn", formIdSet);
        param.put("enable", BasicConstant.IS_USE);
        List<PaasFormEntityExt> paasFormList = paasFormModel.list(param);
        if (CollectionsUtil.isEmpty(paasFormList)) {
            throw new XbbException(ProErrorCodeEnum.API_ERROR_260023);
        }

        List<Long> businessTypeList = new ArrayList<>();
        List<SmartSettingsBusinessListPojo> businessList = new ArrayList<>();
        for (PaasFormEntityExt entityExt : paasFormList) {
            if (SaasMarkEnum.PAAS.getCode().equals(entityExt.getSaasMark())) {
                if (paasMap.containsKey(entityExt.getMenuId())) {
                    SmartSettingsBusinessListPojo pojo = paasMap.get(entityExt.getMenuId());
                    pojo.setName(entityExt.getName());
                    businessList.add(pojo);
                }
            } else if (SaasMarkEnum.SAAS.getCode().equals(entityExt.getSaasMark())) {
                // 工作报告特殊处理
                Long businessType = entityExt.getBusinessType().longValue();
                boolean isWorkReport = businessType == XbbRefTypeEnum.WORKREPORT_DAILY.getCode() ||
                        businessType == XbbRefTypeEnum.WORKREPORT_WEEKLY.getCode() ||
                        businessType == XbbRefTypeEnum.WORKREPORT_MONTHLY.getCode();
                businessType = isWorkReport ? Long.valueOf(XbbRefTypeEnum.WORK_REPORT.getCode()) : businessType;
                if (businessTypeList.contains(businessType)) {
                    continue;
                }
                businessTypeList.add(businessType);
                SmartSettingsBusinessListPojo smartSettingsBusinessListPojo = saasMap.get(businessType);
                if (Objects.nonNull(smartSettingsBusinessListPojo)) {
                    businessList.add(smartSettingsBusinessListPojo);
                }
            }
        }

        // 权限
//        boolean editPermission = businessListDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.SMART_SETTINGS_UPDATE.getAlias());
//        businessListVO.setEditPermission(editPermission);
        businessListVO.setList(businessList);
        return businessListVO;
    }

    @Override
    public SmartSettingsListVO list(SmartSettingsListDTO listDTO) throws XbbException {
        SmartSettingsListVO listVO = new SmartSettingsListVO();

        // 参数校验
        checkSaasMark(listDTO.getSaasMark(), listDTO.getBusinessType(), listDTO.getMenuId());

        String attr = listDTO.getAttr();
        List<SmartSettingsListPojo> list = new ArrayList<>();
        if (attr == null) {
            Map<String, Object> param = BeanUtil.convertBean2Map(listDTO);
            param.put(StringConstant.CORPID, listDTO.getCorpid());
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<AiAssistantEntity> dataList = aiAssistantModel.findEntitys(param);
            for (AiAssistantEntity entity : dataList) {
                SmartSettingsListPojo pojo = new SmartSettingsListPojo();
                BeanUtil.copyProperties(entity, pojo);
                list.add(pojo);
            }
        } else {
            // 表单模板跳转过来传字段attr
            List<AiAssistantEntity> dataList = aiAssistantModel.getListByOneCondition(listDTO.getCorpid(), listDTO.getFormId());
            Integer businessType = listDTO.getBusinessType();
            List<String> aliasIn = new ArrayList<>();
            if (businessType != null) {
                // 对应的attr
                aliasIn = SmartSettingsFieldEnum.getAliasByFormAttr(attr, listDTO.getBusinessType());
            }
            if (aliasIn.isEmpty()) {
                aliasIn.add(attr);
            }

            for (AiAssistantEntity entity : dataList) {
                List<ConditionsEntityExt> conditionList = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
                if (Objects.isNull(conditionList) || conditionList.isEmpty()) {
                    continue;
                }
                String alias = conditionList.get(0).getAttr();
                if (aliasIn.contains(alias)) {
                    SmartSettingsListPojo pojo = new SmartSettingsListPojo();
                    BeanUtil.copyProperties(entity, pojo);
                    // 添加attr和fieldType
                    pojo.setAttr(alias);
                    pojo.setFieldType(conditionList.get(0).getFieldType());
                    list.add(pojo);
                }
            }
        }

        // 权限
//        boolean editPermission = listDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.SMART_SETTINGS_UPDATE.getAlias());
//        boolean delPermission = listDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.SMART_SETTINGS_DELETE.getAlias());
//        listVO.setEditPermission(editPermission);
//        listVO.setDelPermission(delPermission);
        listVO.setList(list);
        return listVO;
    }

    @Override
    public SmartSettingsGetVO get(SmartSettingsGetDTO getDTO) throws XbbException {
        SmartSettingsGetVO getVO = new SmartSettingsGetVO();

        String corpid = getDTO.getCorpid();

        // 智能助手总数是否超限
        if (Objects.isNull(getDTO.getId()) || getDTO.getId().equals(0L)) {
            // 第一期只判断是否只有30个
//            checkPhaseILimit(corpid);
            checkPackageLimit(corpid);
        }

        // 参数校验
        checkSaasMark(getDTO.getSaasMark(), getDTO.getBusinessType(), getDTO.getMenuId());

        Long id = getDTO.getId();
        // 新建时切换表单，数据不受影响
        boolean isSwitch = getDTO.getIsSwitch() == null ? false : getDTO.getIsSwitch();
        Integer businessType = getDTO.getBusinessType();
        Integer saasMark = getDTO.getSaasMark();

        AiAssistantEntity entity = null;
        if (id != null) {
            entity = aiAssistantModel.getByKey(id, corpid);
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "智能助手不存在");
            }
        }

        // 获取表单及可筛选的表单
        List<ItemDataPoJo> formArray = new ArrayList<>();
        PaasFormEntityExt paasFormEntityExt = getFormAndSelectFormArray(getDTO, formArray);
        //兼容getFormAndSelectFormArray()逻辑修改可能出现的空指针问题
        if(Objects.isNull(paasFormEntityExt)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "表单不存在或您暂无此模块表单的使用权限，请联系管理员分配！");
        }
        // 表单字段解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(paasFormEntityExt.getId(), paasFormEntityExt.getCorpid());
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "表单解释不存在");
        }
        List<FieldAttrEntity> explainList = JSONObject.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        explainList.removeIf(fieldAttrEntity -> !ShowTypeEnum.listShow(fieldAttrEntity.getShowType()));
        // 过虑选择产品 TODO 先把选择产品字段隐藏，等进销存上线再放开
        explainList.removeIf(fieldAttrEntity -> Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(), fieldAttrEntity.getFieldType()));

        // 过虑利率等相关字段(机会－机会毛利率/机会毛利、合同－合同毛利率/合同毛利/现金毛利率/现金毛利、报价单－预估毛利率/预估毛利)
        if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(SalesOpportunityEnum.GROSS_PROFIT_RATE.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(SalesOpportunityEnum.GROSS_PROFIT.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
        } else if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType)) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(ContractEnum.GROSS_PROFIT_RATE.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(ContractEnum.GROSS_PROFIT.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(ContractEnum.CASH_PROFIT_RATE.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(ContractEnum.CASH_PROFIT.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(ContractEnum.DISCOUNT.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
        } else if (Objects.equals(XbbRefTypeEnum.QUOTATION.getCode(), businessType)) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(QuotationEnum.GROSS_PROFIT_RATE.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(QuotationEnum.GROSS_PROFIT.getSaasAttr(), fieldAttrEntity.getSaasAttr()));
        }


        //  实际数据
        List<ConditionsEntityExt> triggerCondition = new ArrayList<>();
        Integer action = SmartActionTypeEnum.MESSAGE.getCode();
        SmartStrategyPojo strategy = new SmartStrategyPojo();
        List<OptionalRangeEntity> executor = new ArrayList<>();
        // 短信执行人（paas中字段类型为手机号）
        List<SmartFieldAttrPojo> smsExecutor = new ArrayList<>();
        String memo = "";
        String name = entity != null ? entity.getName() : "";

        // attr是否存在(新建时，设置触发条件)
        String attr = getDTO.getAttr();
        if (attr != null && entity == null) {
            FieldAttrEntity attrEntity = null;
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                if (Objects.equals(attr, fieldAttrEntity.getAttr())) {
                    attrEntity = fieldAttrEntity;
                    break;
                }
            }

            if (attrEntity != null) {
                ConditionsEntityExt entityExt = new ConditionsEntityExt();
                entityExt.setAttr(attr);
                entityExt.setFieldType(attrEntity.getFieldType());
                entityExt.setHasEmpty(0);

                if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
                    // 最后跟进时间（客户/机会/供应商）无法区分是遗忘（客户/机会/供应商）还是无跟进（客户/机会/供应商）,回款（到期/逾期）、付款（到期/逾期）只取第一个
                    List<SmartSettingsFieldEnum> ssFieldEnumList = SmartSettingsFieldEnum.getByFromAttr(attr, businessType);
                    if (ssFieldEnumList.size() >= 1) {
                        SmartSettingsFieldEnum ssFieldEnum = ssFieldEnumList.get(0);
                        // 添加一个条件
                        entityExt.setAttr(ssFieldEnum.getAlias());
                        entityExt.setFieldType(ssFieldEnum.getType());
                    }
                }
                triggerCondition.add(entityExt);
            }
        }

        // 编辑原有表单时加载设置值，切换到其他表单不加载设置值
        if (entity != null && !isSwitch) {
            triggerCondition = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
            action = entity.getAction();
            strategy = JSONObject.toJavaObject(entity.getStrategy(), SmartStrategyPojo.class);
            executor = entity.getExecutor().toJavaList(OptionalRangeEntity.class);
            smsExecutor = entity.getSmsExecutor().toJavaList(SmartFieldAttrPojo.class);
            memo = entity.getMemo();
        }

        // 当前触发条件的attr列表
        List<String> currentAttrList = new ArrayList<>();

        // 为区分是日报/周报/月报，把数据存入触发条件里，fielType里存报告类型
        if (SaasMarkEnum.SAAS.getCode().equals(saasMark) && Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType)) {
            Integer subBusinessType = paasFormEntityExt.getBusinessType();
            WorkReportTypeEnum reportTypeEnum = WorkReportTypeEnum.getByBusinessType(subBusinessType);
            ConditionsEntityExt entityExt = new ConditionsEntityExt();
            entityExt.setFieldType(reportTypeEnum.getType());
            triggerCondition.clear();
            triggerCondition.add(entityExt);
        } else {
            for (ConditionsEntityExt entityExt : triggerCondition) {
                currentAttrList.add(entityExt.getAttr());
            }
        }


        if (currentAttrList.isEmpty()) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(BasicConstant.ZERO, fieldAttrEntity.getVisible()));
            explainList.removeIf(fieldAttrEntity -> Objects.equals(BasicConstant.ZERO, fieldAttrEntity.getIsOpen()));
        } else {
            Iterator<FieldAttrEntity> it = explainList.iterator();
            while (it.hasNext()) {
                FieldAttrEntity attrEntity = it.next();
                if (!Objects.equals(BasicConstant.ZERO, attrEntity.getVisible()) && !Objects.equals(BasicConstant.ZERO, attrEntity.getIsOpen())) {
                    continue;
                }
                if (currentAttrList.contains(attrEntity.getAttr())) {
                    attrEntity.setAttrName(attrEntity.getAttrName() + "（未启用）");
                } else {
                    it.remove();
                }
            }

        }


        // 数据加载
        getVO.setId(id);
        getVO.setName(name);
        getVO.setMenuId(paasFormEntityExt.getMenuId());
        getVO.setFormId(paasFormEntityExt.getId());
        getVO.setAppId(paasFormEntityExt.getAppId());
        getVO.setFormName(paasFormEntityExt.getName());
        getVO.setFormArray(formArray);
        getVO.setBusinessType(businessType);
        getVO.setSaasMark(getDTO.getSaasMark());
        getVO.setTriggerCondition(triggerCondition);

        getVO.setMemo(memo);
        getVO.setAction(action);
        //执行时间暂时设置默认为2,每天(去掉  只执行一次 )
        if (Objects.isNull(strategy.getStrategyType())){
            strategy.setStrategyType(2);
        }
        getVO.setStrategy(strategy);
        getVO.setExecutor(executor);
        getVO.setSmsExecutor(smsExecutor);


        // 触发条件可选字段
        triggerFieldList(getVO, saasMark, businessType, explainList);
        // 触发条件字段可选项
        fieldConditionList(getVO, saasMark);
        // 执行设置可选项列表
        strategyConditionList(getVO, saasMark, businessType);
        // 可选动态负责人列表
        dynamicManagerList(getVO, saasMark, businessType);
        // paas数字字段对应的执行人
        smsExecutorList(getVO, saasMark, businessType, explainList);

        return getVO;
    }

    @Override
    public SmartSettingsConditionValueVO getConditionValue(SmartSettingsConditionValueDTO conditionValueDTO) throws XbbException {
        SmartSettingsConditionValueVO conditionValueVO = new SmartSettingsConditionValueVO();

        PaasFormEntityExt formEntityExt = paasFormModel.getByKey(conditionValueDTO.getFormId(), conditionValueDTO.getCorpid());
        if (formEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "表单不存在");
        }

        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(conditionValueDTO.getFieldType());
        SmartSettingsFieldEnum smartFieldEnum = SmartSettingsFieldEnum.getFieldTypeEnum(conditionValueDTO.getFieldType());
        if (fieldTypeEnum == null && smartFieldEnum == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "字段类型不正确");
        }

        List<ItemDataPoJo> items = new ArrayList<>();
        // 提交时间/修改时间、日期、音频
        if (fieldTypeEnum != null) {
            switch (fieldTypeEnum) {
                // 提交时间/修改时间、日期、音频
                // 输入值，不用查询
                case DATETIME:
                case ADDTIME:
                case UPDATETIME:
                case VIDEO:
                    break;
                default:
                    SearchDataInConditionDTO searchDataInConditionDTO = new SearchDataInConditionDTO();
                    BeanUtil.copyProperties(conditionValueDTO, searchDataInConditionDTO);
                    SearchDataInConditionVO searchDataInConditionVO = paasFormDataService.searchDataInProcessCondition(searchDataInConditionDTO);
                    items = searchDataInConditionVO.getItems() != null ? searchDataInConditionVO.getItems() : items;
                    break;
            }
        } else {
            switch (smartFieldEnum) {
                // 销售阶段
                case OPPORTUNITY_STAGE:
                   //销售机会阶段(需要去掉赢单,流失)
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("corpid",conditionValueDTO.getCorpid());
                    param.put("typeIn",Collections.singletonList(0));
                    param.put("formId",conditionValueDTO.getFormId());
                    param.put("del",0);
                    List<SaleStageEntity> entitys = saleStageModel.findEntitys(param);
                    for (SaleStageEntity entity : entitys){
                            ItemDataPoJo itemPoJo = new ItemDataPoJo();
                            itemPoJo.setText(entity.getName());
                            itemPoJo.setValue(entity.getCode());
                            items.add(itemPoJo);
                    }
                    break;
                // 其他为输入框或无可选值，不用查询
                default:
                    break;
            }
        }
        conditionValueVO.setList(items);

        return conditionValueVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SmartSettingsSaveVO save(SmartSettingsSaveDTO saveDTO) throws XbbException {
        SmartSettingsSaveVO saveVO = new SmartSettingsSaveVO();

        // 参数校验
        checkSaasMark(saveDTO.getSaasMark(), saveDTO.getBusinessType(), saveDTO.getMenuId());
        checkSmartStrategy(saveDTO.getStrategy());
        checkTriggerCondition(saveDTO.getBusinessType(), saveDTO.getTriggerCondition(), saveDTO.getNewTriggerCondition());
//        boolean saasSmsFlag = Objects.equals(SmartActionTypeEnum.SMS.getCode(), saveDTO.getAction()) &&
//                Objects.equals(SaasMarkEnum.SAAS.getCode(), saveDTO.getSaasMark());
//        // 执行动作为短信时，saas执行人为空，paas执行人表单字段
//        if (!saasSmsFlag) {
//            if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saveDTO.getSaasMark())) {
//                if (saveDTO.getSmsExecutor() == null || saveDTO.getSmsExecutor().size() == 0) {
//                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028.getCode(), "执行人不能为空");
//                }
//            }
//        }


        String corpid = saveDTO.getCorpid();

        boolean isAdd = false;
        AiAssistantEntity oldEntity = new AiAssistantEntity();
        AiAssistantEntity entity = new AiAssistantEntity();
        Long id = saveDTO.getId();
        if (id == null || id == 0) {
            isAdd = true;
            // 套餐的判断
            checkPackageLimit(corpid);
            // 默认不启用
            entity.setEnable(BasicConstant.NO_USE);
        } else {
            oldEntity = aiAssistantModel.getByKey(id, corpid);
            if (oldEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "数据不存在");
            }
            BeanUtil.copyProperties(oldEntity, entity);
            entity.setUpdateTime((long) DateUtil.getInt());
        }

        // 设置默认执行周期
        SmartStrategyPojo strategyPojo = saveDTO.getStrategy();
        if (strategyPojo.getStrategyCycle() == null) {
            strategyPojo.setStrategyCycle(1);
        }

        BeanUtil.copyProperties(saveDTO, entity);
        // 触发条件，执行策略，执行人
        JSONArray triggerCondition = new JSONArray();
        triggerCondition.addAll(saveDTO.getTriggerCondition());

        String strategyStr = JSON.toJSONString(strategyPojo);
        JSONObject strategy = JsonHelperUtil.parseObject(strategyStr);
        JSONArray executor = new JSONArray();
        executor.addAll(saveDTO.getExecutor());
        // 短信执行人
        JSONArray smsExecutor = new JSONArray();
        smsExecutor.addAll(saveDTO.getSmsExecutor());

        entity.setTriggerCondition(triggerCondition);
        entity.setStrategy(strategy);
        entity.setExecutor(executor);
        entity.setSmsExecutor(smsExecutor);
        entity.setAppId(saveDTO.getAppId());

        try {
            aiAssistantModel.save(entity);
        } catch (Exception e) {
            LOG.error("智能助手保存失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        String loginUserName = saveDTO.getLoginUserName();
        OperateTypeEnum operateTypeEnum = isAdd ? OperateTypeEnum.NEW : OperateTypeEnum.EDIT;
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_AI_ASSISTANT), loginUserName + operateTypeEnum.getName(), entity.getName());
        if (isAdd) {
            OperateLogEntity logEntity = new OperateLogEntity(corpid, saveDTO.getUserId(), loginUserName, OperateModuleTypeEnum.AI_ASSISTANT,
                    operateTypeEnum, entity.getId().toString(), ControlCenterMenuEnum.AI_ASSISTANT.getName(), memo, saveDTO.getHttpHeader(), null);
            operateLogModel.insert(logEntity);
        } else {
            JSONObject oldObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(oldEntity));
            JSONObject newObj = JsonHelperUtil.parseObject(JSONObject.toJSONString(entity));
            // 触发条件

            List<DetailLogPojo> detailArr = logHelp.deatilLog4AiAssistant(corpid, oldObj, newObj, saveDTO.getOldTriggerCondition(), saveDTO.getNewTriggerCondition());
            mongoLogHelp.buildLog4DetailArr(detailArr, corpid, saveDTO.getUserId(), loginUserName, OperateModuleTypeEnum.AI_ASSISTANT, OperateTypeEnum.EDIT, id.toString(), ProPermissionAliasEnum.AI_ASSISTANT.getMemo(), memo, saveDTO.getHttpHeader());
        }

        saveVO.setId((entity.getId()).intValue());
        return saveVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SmartSettingsEnableVO enable(SmartSettingsEnableDTO enableDTO) throws XbbException {
        SmartSettingsEnableVO enableVO = new SmartSettingsEnableVO();

        String corpid = enableDTO.getCorpid();
        Integer enable = enableDTO.getEnable();
        boolean isEnable = BasicConstant.IS_USE.equals(enable);
        AiAssistantEntity entity = aiAssistantModel.getByKey(enableDTO.getId(), corpid);
        if (entity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "数据不存在");
        }
        String enableStr = isEnable ? "启用" : "关闭";
        if (entity.getEnable().equals(enable)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "无需重复" + enableStr);
        }
        if (isEnable) {
            // 当前启用的数量
            // 套餐的判断
            checkPackageLimit(corpid);

            // 是否选择了短信模板
            if (Objects.equals(SmartActionTypeEnum.SMS.getCode(), entity.getAction()) && StringUtil.isEmpty(entity.getMemo())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "请点击编辑，选择短信模板后开启");
            }
        }


        entity.setEnable(enableDTO.getEnable());
        entity.setUpdateTime((long) DateUtil.getInt());
        try {
            aiAssistantModel.update(entity);
        } catch (Exception e) {
            LOG.error("智能助手" + enableStr + "失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        String key = corpid + "_"+ ValueAddedTypeEnum.AI_ASSISTANT.getType();
        paasRedisHelper.removeValue(RedisPrefixConstant.VALUE_ADDED, key);
        // 日志
        String loginUserName = enableDTO.getLoginUserName();
        OperateTypeEnum operateTypeEnum = enable.equals(BasicConstant.NO_USE) ? OperateTypeEnum.CLOSE : OperateTypeEnum.ENABLE;
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_AI_ASSISTANT_ENABLE), loginUserName + enableStr, entity.getName());
        OperateLogEntity logEntity = new OperateLogEntity(corpid, enableDTO.getUserId(), loginUserName, OperateModuleTypeEnum.AI_ASSISTANT,
                operateTypeEnum, entity.getId().toString(), ControlCenterMenuEnum.AI_ASSISTANT.getName(), memo, enableDTO.getHttpHeader(), null);
        operateLogModel.insert(logEntity);

        return enableVO;
    }

    @Override
    public SmartSettingsMenuListVO menuList(MenuNewListDTO menuListDTO) throws XbbException {
        SmartSettingsMenuListVO menuListVO = new SmartSettingsMenuListVO();

        Map<String, Object> param = BeanUtil.convertBean2Map(menuListDTO);
        param.put(StringConstant.CORPID, menuListDTO.getCorpid());
        param.put("orderByStr", "sort");
//        param.put("saasMark", SaasMarkEnum.SAAS.getCode());
        List<PaasAppEntity> appList = paasAppModel.list(param);
        if (Objects.isNull(appList)) {
            appList = new ArrayList<>();
        }

        Map<Long, List<AppMenuListVO>> menuListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.clear();
        param.put(StringConstant.CORPID, menuListDTO.getCorpid());
        param.put("enable", menuListDTO.getEnable());
        param.put("orderByStr", "app_id, sort");
        param.put("del", DelEnum.NORMAL.getDel());
        // 只显示saas的菜单
//        param.put("saasMark", SaasMarkEnum.SAAS.getCode());
        List<PaasMenuEntity> menuList = paasMenuModel.list(param);
        if (menuList == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
        }
        List<AppMenuListVO> menuExtList = new ArrayList<>();
        Map<Long, List<AppMenuListVO>> menuMap = new HashMap<>(menuList.size());
        for (PaasMenuEntity paasMenuEntity : menuList) {
            // 过虑菜单：模拟生产、签到管理、工单、跟进记录(客户/供应商）、审批、短信、呼叫中心、客户子菜单、机会子菜单
            // 过滤菜单：访客计划
            // 过滤菜单：入库单、出库单
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByAlias(paasMenuEntity.getAlias());
            if (filterApp(paasMenuEntity.getAlias())) {
                continue;
            }
            // 暂时先过滤经销商和订单中心
            if (Objects.equals(paasMenuEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())){
                continue;
            }

            AppMenuListVO appMenuListVO = new AppMenuListVO();
            BeanUtil.copyProperties(paasMenuEntity, appMenuListVO);
            appMenuListVO.setBusinessType(xbbRefTypeEnum.getCode());

            if (paasMenuEntity.getParentId() == 0) {
                // 存放一级菜单
                menuExtList.add(appMenuListVO);
            } else {
                // 获取二级菜单，并放到容器中
                if (Objects.isNull(menuMap.get(paasMenuEntity.getParentId()))) {
                    List<AppMenuListVO> paasMenuList = new ArrayList<>();
                    paasMenuList.add(appMenuListVO);
                    menuMap.put(paasMenuEntity.getParentId(), paasMenuList);
                } else {
                    List<AppMenuListVO> paasMenuList = menuMap.get(paasMenuEntity.getParentId());
                    paasMenuList.add(appMenuListVO);
                    menuMap.put(paasMenuEntity.getParentId(), paasMenuList);
                }
            }
        }
        
        //过滤出所有menus,key为parentid
        Map<Long, List<PaasMenuEntity>> map = menuList.stream().collect(Collectors.groupingBy(t -> t.getParentId()));
    
        // 将子菜单放入父菜单
        List<AppMenuListVO> paasMenuEntityList = new ArrayList<>();
        if (!menuExtList.isEmpty()) {
            menuExtList.forEach((item) -> {
                AppMenuListVO appMenuListVO = new AppMenuListVO();
                BeanUtil.copyProperties(item, appMenuListVO);
                //38368 【智能助手】新增助手弹窗选不到客户管理模块
                //如果是group的, 三级菜单没有值就跳过
                if (Objects.equals(item.getType(), MenuTypeEnum.GROUP.getType()) && CollectionsUtil.isEmpty(map.get(item.getId()))) {
                    return;
                }

                List<AppMenuListVO> subMenuList = menuMap.get(item.getId());
                if (Objects.nonNull(subMenuList)) {
                    //有三级菜单的需要将二级菜单也放入三级菜单中
                    AppMenuListVO mainMenuListVO = new AppMenuListVO();
                    BeanUtil.copyProperties(item, mainMenuListVO);
                    mainMenuListVO.setType(MenuTypeEnum.FORM.getType());
                    subMenuList.add(0, mainMenuListVO);
                    appMenuListVO.setSubMenuList(subMenuList);
                }
                paasMenuEntityList.add(appMenuListVO);
            });
        }
        // 将菜单列表分应用存放到容器中
        for (AppMenuListVO item : paasMenuEntityList) {
            if (Objects.isNull(menuListMap.get(item.getAppId()))) {
                List<AppMenuListVO> paasMenuList = new ArrayList<>();
                paasMenuList.add(item);
                menuListMap.put(item.getAppId(), paasMenuList);
            } else {
                List<AppMenuListVO> paasMenuList = menuListMap.get(item.getAppId());
                paasMenuList.add(item);
                menuListMap.put(item.getAppId(), paasMenuList);
            }
        }

        List<PaasAppMenuVO> appVOList = new ArrayList<>();
        //套餐是标准版 或者 "市场管理"应用未开启
        boolean feeTypeIsStandardOrAppIsClosedFlag = marketManagementBusinessHelp.feeTypeIsStandardOrAppIsClosed(menuListDTO.getCorpid());
        appList.forEach((item) -> {
            List<AppMenuListVO> menuListVOList = menuListMap.get(item.getId());
            if (Objects.nonNull(menuListVOList)) {
                //管理中心-"智能助手"判断，菜单是否需要放入"市场管理"
                if(Objects.equals(SystemAppMenuEnum.MARKET_MANAGEMENT.getAlias(), item.getAlias()) && feeTypeIsStandardOrAppIsClosedFlag){
                    return;
                }
                PaasAppMenuVO paasAppMenuVO = new PaasAppMenuVO();
                BeanUtil.copyProperties(item, paasAppMenuVO);
                paasAppMenuVO.setSubMenuList(menuListVOList);
                appVOList.add(paasAppMenuVO);
            }
        });
        menuListVO.setMenuList(appVOList);
        return menuListVO;
    }
    
    @Override
    public SmartSettingsDelVO delete(SmartSettingsDelDTO smartSettingsDelDTO) throws XbbException {
        SmartSettingsDelVO smartSettingsDelVO = new SmartSettingsDelVO();

        Long id = smartSettingsDelDTO.getId();
        String corpid = smartSettingsDelDTO.getCorpid();

        AiAssistantEntity entity = aiAssistantModel.getByKey(id, corpid);
        if (entity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "数据不存在");
        }

        try {
            aiAssistantModel.deleteByKey(id, corpid);
        } catch (Exception e) {
            LOG.error("智能助手删除失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        String loginUserName = smartSettingsDelDTO.getLoginUserName();
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), loginUserName , OperateModuleTypeEnum.AI_ASSISTANT.getName(), entity.getName());
        OperateLogEntity logEntity = new OperateLogEntity(corpid, smartSettingsDelDTO.getUserId(), loginUserName, OperateModuleTypeEnum.AI_ASSISTANT,
                OperateTypeEnum.DELETE, entity.getId().toString(), ControlCenterMenuEnum.AI_ASSISTANT.getName(), memo, smartSettingsDelDTO.getHttpHeader(), null);
        operateLogModel.insert(logEntity);
        String key = corpid + "_"+ ValueAddedTypeEnum.AI_ASSISTANT.getType();
        paasRedisHelper.removeValue(RedisPrefixConstant.VALUE_ADDED, key);
        smartSettingsDelVO.setId(id.intValue());
        return smartSettingsDelVO;
    }

    @Override
    public void batchDisable(String corpid, String loginUserId, String loginUserName, String httpHeader, PaasAppEntity appEntity, PaasMenuEntity menuEntity) throws XbbException {
        Integer saasMark = null;
        String alias = null;
        Long menuId = null;
        String linkName = "";

        if (Objects.nonNull(appEntity)) {
            // 应用下的智能助手
            saasMark = appEntity.getSaasMark();
            alias = appEntity.getAlias();
            linkName = appEntity.getName() + "应用";
        } else if (Objects.nonNull(menuEntity)) {
            // 业务下的智能助手
            saasMark = menuEntity.getSaasMark();
            alias = menuEntity.getAlias();
            menuId = menuEntity.getId();
            linkName = menuEntity.getName() + "菜单";
        }

        List<AiAssistantEntity> list = null;
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) && Objects.nonNull(alias)) {
            list = getListByAlias(corpid, alias);
        } else if (Objects.nonNull(menuId)) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(StringConstant.CORPID, corpid);
            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("menuId", menuId);
            list = aiAssistantModel.findEntitys(param);
        }
        if (Objects.isNull(list) || list.isEmpty()) {
            return;
        }

        StringBuffer nameBuffer = new StringBuffer();
        long now = DateUtil.getInt();
        for (AiAssistantEntity entity : list) {
            entity.setEnable(BasicConstant.NO_USE);
            entity.setUpdateTime(now);
            if (nameBuffer.length() == BasicConstant.ZERO) {
                nameBuffer.append(entity.getName());
            } else {
                nameBuffer.append("、").append(entity.getName());
            }
        }

        try {
            aiAssistantModel.updateBatch(list, corpid);
        } catch (Exception e) {
            LOG.error("智能助手关闭失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 日志
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.CLOSE;
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_AI_ASSISTANT_ENABLE), loginUserName + "通过关闭" + linkName + operateTypeEnum.getName(), nameBuffer.toString());
        OperateLogEntity logEntity = new OperateLogEntity(corpid, loginUserId, loginUserName, OperateModuleTypeEnum.AI_ASSISTANT,
                operateTypeEnum, null, ControlCenterMenuEnum.AI_ASSISTANT.getName(), memo, httpHeader, null);
        operateLogModel.insert(logEntity);
    }

    /**
     * 获取需要关闭的智能助手
     *
     * @param corpid 公司id
     * @param alias 业务对应的alias
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-12-24 09:14
     * @since v4.9.0
     * @version v4.9.0
     */
    private List<AiAssistantEntity> getListByAlias(String corpid, String alias) {
        boolean isJxc = false;
        List<Integer> businessTypeList = new ArrayList<>();
        XbbRefTypeEnum typeEnum = XbbRefTypeEnum.getByAlias(alias);
        switch (typeEnum) {
            case CRM:
                businessTypeList.addAll(getCrmCodeList());
                // 回款，发票
                businessTypeList.add(XbbRefTypeEnum.PAYMENT.getCode());
                businessTypeList.add(XbbRefTypeEnum.INVOICE.getCode());
                break;
            case JXC:
                businessTypeList.addAll(getJxcCodeList());
                // 合同（待）、产品（预警）、付款
                businessTypeList.add(XbbRefTypeEnum.CONTRACT.getCode());
                businessTypeList.add(XbbRefTypeEnum.PRODUCT.getCode());
                businessTypeList.add(XbbRefTypeEnum.PAY_PLAN.getCode());
                isJxc = true;
                break;
            case UNKNOWN:
                break;
            default:
                businessTypeList.add(typeEnum.getCode());
                break;
        }
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("businessTypeIn", businessTypeList);
        param.put("enable", BasicConstant.IS_USE);
        List<AiAssistantEntity> list = aiAssistantModel.findEntitys(param);
        if (Objects.isNull(list) || list.isEmpty()) {
            return list;
        }

        if (isJxc) {
            Iterator<AiAssistantEntity> it = list.iterator();
            while (it.hasNext()) {
                // 过虑非进销存部分（合同、产品）
                AiAssistantEntity entity = it.next();
                if (!Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), entity.getBusinessType()) &&
                    !Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), entity.getBusinessType())) {
                    continue;
                }
                AiAssistantPushTypeEnum pushTypeEnum = smartSettingsHelp.otherPush(entity);
                if (Objects.isNull(pushTypeEnum)) {
                    it.remove();
                }
            }
        }
        return list;
    }

    /**
     * 应用校验
     *
     * @param saasMark     saas/paas标识
     * @param businessType 业务类型
     * @param menuId       菜单id
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-24 21:48
     * @version v1.0
     * @since v1.0
     */
    private void checkSaasMark(Integer saasMark, Integer businessType, Long menuId) throws XbbException {
        if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
            XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            if (XbbRefTypeEnum.UNKNOWN.equals(refTypeEnum)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "SAAS内未知业务类型");
            } else {
                // 不支持智能助手的业务:签到管理、工单、短信、呼叫中心、模拟生产
                List<Integer> noSmartList = Arrays.asList(XbbRefTypeEnum.SIGNIN.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(),
                        XbbRefTypeEnum.GROUP_MESSAGE.getCode(), XbbRefTypeEnum.CALL_CENTER.getCode(),
                        XbbRefTypeEnum.SIMULATED_PRODUCTION.getCode());
                if (noSmartList.contains(businessType)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "SAAS内不支持的业务类型");
                }
            }
        } else if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
            if (menuId == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "PAAS内未知业务类型");
            }
        } else {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "SAASMark业务标识未知类型");
        }
    }

    /**
     * 校验执行策略
     *
     * @param strategyPojo 执行策略
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-25 09:39
     * @version v1.0
     * @since v1.0
     */
    private void checkSmartStrategy(SmartStrategyPojo strategyPojo) throws XbbException {
        Integer strategyType = strategyPojo.getStrategyType();
        StrategyTypeEnum typeEnum = StrategyTypeEnum.getByCode(strategyType);
        if (typeEnum == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "执行时间策略不正确");
        }
        if (StrategyTypeEnum.CUSTOM.getCode().equals(strategyType)) {
            Integer customType = strategyPojo.getCustomType();
            CustomStrategyTypeEnum customTypeEnum = CustomStrategyTypeEnum.getByCode(customType);
            if (customTypeEnum == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "自定义策略类型不正确");
            } else if (CustomStrategyTypeEnum.WEEKLY.getCode().equals(customType)) {
                WeekEnum weekEnum = WeekEnum.getByCode(strategyPojo.getStrategyWeek());
                if (weekEnum == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "星期的日期类型不正确");
                }
            }
            if (strategyPojo.getStrategyCycle() == null || strategyPojo.getStrategyCycle() < 1) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "执行次数不能小于1");
            }
        } else if (StrategyTypeEnum.WEEKLY.getCode().equals(strategyType)) {
            WeekEnum weekEnum = WeekEnum.getByCode(strategyPojo.getStrategyWeek());
            if (weekEnum == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "星期的日期类型不正确");
            }
        }
    }

    /**
     * 校验触发条件
     *
     * @param businessType 业务类型
     * @param triggerConditions 触发条件
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-12-23 10:17
     * @since v4.9.0
     * @version v4.9.0
     */
    private void checkTriggerCondition(Integer businessType, List<ConditionsEntityExt> triggerConditions, List<AiTriggerConditionLogPojo> newTriggerCondition) throws XbbException {
        /**
         * 1.合同的待（采购、生产、出库）不能同时存在；
         * 2.产品的预警和过期日期不能同是存在；
         * 3.包含任意一个/同时包含/等于任意一个/不等于任意一个（限20个）
         */
        boolean isContract = Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType);
        boolean isProduct = Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType);
        // 工作报告不效验
        if (Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType)) {
            return;
        }
        Map<String, String> attrNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (AiTriggerConditionLogPojo pojo : newTriggerCondition) {
            attrNameMap.put(pojo.getAttr(), pojo.getAttrName());
        }

        // 合同待条件
        List<Integer> waitFieldTypeList = Arrays.asList(SmartSettingsFieldEnum.WAIT_PURCHASE.getType(),
                SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getType(), SmartSettingsFieldEnum.WAIT_OUTSTOCK.getType());
        // 产品保质日期＆上限下限 --> 上限1，下限1，保质日期2，大于3报错
        Map<Integer, Integer> stockMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        stockMap.put(SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getType(), 1);
        stockMap.put(SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getType(), 1);
        stockMap.put(SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getType(), 2);

        int waitCount = 0;
        int stockCount = 0;

        for (ConditionsEntityExt entityExt : triggerConditions) {
            // 条件：包含任意一个/同时包含/等于任意一个/不等于任意一个
            boolean isInclude = Objects.equals(ConditionEnum.INCLUDE.getSymbol(), entityExt.getSymbol())
                    || Objects.equals(ConditionEnum.ALLINCLUDE.getSymbol(), entityExt.getSymbol())
                    || Objects.equals(ConditionEnum.IN.getSymbol(), entityExt.getSymbol())
                    || Objects.equals(ConditionEnum.NOIN.getSymbol(), entityExt.getSymbol());
            String attrName = attrNameMap.get(entityExt.getAttr());

            SmartSettingsFieldEnum ssFieldEnum = SmartSettingsFieldEnum.getFieldTypeEnum(entityExt.getFieldType());
            if (isInclude && entityExt.getValue().size() > AiAssistantConstant.MAX_INCLUDE_COUNT) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, attrName + "最多只能包含" + AiAssistantConstant.MAX_INCLUDE_COUNT + "个值");
            }
            if (Objects.nonNull(ssFieldEnum)) {
                if (isContract && waitFieldTypeList.contains(entityExt.getFieldType())) {
                    waitCount ++;
                } else if (isProduct && stockMap.containsKey(entityExt.getFieldType())) {
                    stockCount += stockMap.get(entityExt.getFieldType());
                }
            }
        }
        if (isContract && waitCount > BasicConstant.ONE) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "不能同时设置待采购、待生产、待出库条件");
        } else if (isProduct && stockCount > BasicConstant.TWO) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, "“产品过期日期”不能和“库存预警下限”、“库存预警上限”同时设置");
        }

    }

    /**
     * 一期的数量是否超限
     *
     * @param corpid 公司id
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-12-24 20:06
     * @since v4.9.0
     * @version v4.9.0
     */
    private void checkPhaseILimit(String corpid) throws XbbException {
        // 获取智能助手总数
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        int count = aiAssistantModel.getEntitysCount(param);
        String payNum = companyConfigService.getCompanyConfigSetValue(corpid, CompanyConfigEnum.AI_ASSISTANT_NUM.getAlias());
        // 当前的总数量
        int totalNum = Integer.valueOf(payNum) + AiAssistantConstant.MAX_PHASE_I;
        if (count >= totalNum) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "最多只能添加" + totalNum + "个");
        }
    }


    /**
     * 检验智能助手数量是否超过限制
     *
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-21 11:11
     * @version v1.0
     * @since v1.0
     */
    private void checkPackageLimit(String corpid) throws XbbException {
        // 获取智能助手总数
        JSONObject jsonObject = packageService.getValueAddInfo(corpid, ValueAddedTypeEnum.AI_ASSISTANT, null, null);
        Integer totalCount = jsonObject.getInteger("totalValue");
        Integer usedValue = jsonObject.getInteger("usedValue");
        Integer num = usedValue - totalCount;
        // 获取套餐类型

        if (num>=0) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100094, String.format(SystemErrorCodeEnum.API_ERROR_100094.getMsg(), totalCount));
        }
    }

    /**
     * 获取智能助手当前的表单和可用表单列表
     *
     * @param getDTO    入参
     * @param formArray 表单可选列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-21 14:10
     * @version v1.0
     * @since v1.0
     */
    private PaasFormEntityExt getFormAndSelectFormArray(SmartSettingsGetDTO getDTO, List<ItemDataPoJo> formArray) throws XbbException {

        PaasFormEntityExt paasFormEntityExt = null;
        // 直接新建paas智能助手
        String corpid = getDTO.getCorpid();
        Integer saasMark = getDTO.getSaasMark();
        Long formId = getDTO.getFormId();
        Integer businessType = getDTO.getBusinessType();
        // ===============   paas表单 ===================
        if (getDTO.getMenuId() != null && SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
            paasFormEntityExt = paasFormModel.getByMenuId(getDTO.getMenuId(), corpid);
            if (paasFormEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "表单不存在");
            }
            ItemDataPoJo pojo = new ItemDataPoJo(paasFormEntityExt.getName(), paasFormEntityExt.getId());
            formArray.add(pojo);

            return paasFormEntityExt;
        }

        // ================  saas表单 ==================
        if (formId != null) {
            paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            if (paasFormEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, "表单不存在");
            }
        }
        // 获取可筛选的表单
        List<Integer> businessTypeList = new ArrayList<>();
        // 工作报告做特殊处理
        if (businessType == XbbRefTypeEnum.WORK_REPORT.getCode()) {
            businessTypeList.add(XbbRefTypeEnum.WORKREPORT_DAILY.getCode());
            businessTypeList.add(XbbRefTypeEnum.WORKREPORT_WEEKLY.getCode());
            businessTypeList.add(XbbRefTypeEnum.WORKREPORT_MONTHLY.getCode());
        } else {
            businessTypeList.add(businessType);
        }
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put(StringConstant.CORPID, corpid);
        map.put("del", DelEnum.NORMAL.getDel());
        map.put("enable", BasicConstant.IS_USE);
        map.put("businessTypeList", businessTypeList);
        List<PaasFormEntityExt> formList = paasFormModel.list(map);
        //过滤掉没有使用权限的多模板表单
        formList = filterNoPermissionForm(formList,getDTO);
        if (formList.size() > 0) {
            if (formId == null) {
                paasFormEntityExt = formList.get(0);
                for (PaasFormEntityExt entityExt : formList) {
                    ItemDataPoJo pojo = new ItemDataPoJo(entityExt.getName(), entityExt.getId());
                    formArray.add(pojo);
                }
            } else {
                List<Long> formIdList = new ArrayList<>();
                formList.forEach(item->{
                    formIdList.add(item.getId());
                });
                for (PaasFormEntityExt entityExt : formList) {
                    ItemDataPoJo pojo = new ItemDataPoJo(entityExt.getName(), entityExt.getId());
                    formArray.add(pojo);
                }
                if (!formIdList.contains(formId)) {
                    ItemDataPoJo pojo = new ItemDataPoJo(paasFormEntityExt.getName(), paasFormEntityExt.getId());
                    formArray.add(pojo);
                }
            }
        }

        return paasFormEntityExt;
    }

    /***
     * 过滤掉没有使用权限的表单
     * @param formList
     * @param getDTOt
     */
    private List<PaasFormEntityExt> filterNoPermissionForm(List<PaasFormEntityExt> formList , SmartSettingsGetDTO getDTOt){
        List<PaasFormEntityExt> perssionFormList =  new ArrayList<>();
        if(CollectionsUtil.isNotEmpty(formList)) {
            for(PaasFormEntityExt paasFormEntityExt : formList){
                List<OptionalRangeEntity> optionalRangeList = JSONObject.parseArray(paasFormEntityExt.getPermission(), OptionalRangeEntity.class);
                Boolean noPermission = optionalRangeList != null && !optionalRangeList.isEmpty() && paasFormHelp.haveNoPermission(getDTOt.getLoginUser(), optionalRangeList);
                if (Objects.equals(paasFormEntityExt.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(paasFormEntityExt.getBusinessType()) && noPermission) {
                    continue;
                }
                perssionFormList.add(paasFormEntityExt);
            }
        }
        return  perssionFormList;
    }

    /**
     * 设置执行设置可选项列表
     *
     * @param getVO        前端需要数据
     * @param saasMark     saas/paas标识枚举
     * @param businessType 业务类型
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-25 20:04
     * @version v1.0
     * @since v1.0
     */
    private void strategyConditionList(SmartSettingsGetVO getVO, Integer saasMark, Integer businessType) {
        // 执行设置可选项：执行动作，执行策略，自定义策略，执行日期（周），占位符
        List<ItemDataPoJo> actionArray = new ArrayList<>();
        // 消息
        ItemDataPoJo messagePojo = new ItemDataPoJo(SmartActionTypeEnum.MESSAGE.getMemo(), SmartActionTypeEnum.MESSAGE.getCode());
        // 短信
//        ItemDataPoJo smsPojo = new ItemDataPoJo(SmartActionTypeEnum.SMS.getMemo(), SmartActionTypeEnum.SMS.getCode());
        actionArray.add(messagePojo);
        // TODO 一期砍掉访客计划&短信 2019-12-20
//        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
//            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
//            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT, xbbRefTypeEnum)) {
//                // 访客计划
//                ItemDataPoJo communicatePlanPojo = new ItemDataPoJo(SmartActionTypeEnum.ADD_COMMUNICATE_PLAN.getMemo(),
//                        SmartActionTypeEnum.ADD_COMMUNICATE_PLAN.getCode());
//                actionArray.add(communicatePlanPojo);
//                // 短信
//                actionArray.add(smsPojo);
//            }
//        } else if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
//            // 短信
//            actionArray.add(smsPojo);
//        }

        // 执行策略
        List<ItemDataPoJo> strategyTypeArray = new ArrayList<>();
        List<StrategyTypeEnum> strategyTypeEnumList = StrategyTypeEnum.getAllEnum();
        strategyTypeEnumList.forEach(item -> {
            // TODO 先隐藏自定义执行策略，2019.8.23  隐藏只执行一次－－2019.12.27
            if(!Objects.equals(StrategyTypeEnum.CUSTOM.getCode(), item.getCode()) && !Objects.equals(StrategyTypeEnum.ONLY_ONE.getCode(), item.getCode())) {
                ItemDataPoJo pojo = new ItemDataPoJo(item.getMemo(), item.getCode());
                strategyTypeArray.add(pojo);
            }
        });
        List<ItemDataPoJo> customTypeArray = new ArrayList<>();
        List<CustomStrategyTypeEnum> customStrategyTypeEnumList = CustomStrategyTypeEnum.getAllEnum();
        customStrategyTypeEnumList.forEach(item -> {
            ItemDataPoJo pojo = new ItemDataPoJo(item.getMemo(), item.getCode());
            customTypeArray.add(pojo);
        });
        List<ItemDataPoJo> strategyWeekArray = new ArrayList<>();
        List<WeekEnum> weekEnumList = WeekEnum.getAllEnum();
        weekEnumList.forEach(item -> {
            ItemDataPoJo pojo = new ItemDataPoJo(item.getName(), item.getCode());
            strategyWeekArray.add(pojo);
        });

        getVO.setActionArray(actionArray);
        getVO.setStrategyTypeArray(strategyTypeArray);
        getVO.setCustomTypeArray(customTypeArray);
        getVO.setStrategyWeekArray(strategyWeekArray);
        getVO.setPlaceholder(smartSettingsHelp.getPlaceHolder(saasMark, businessType));
    }


    /**
     * 设置可选择的字段
     *
     * @param getVO        前端需要数据
     * @param saasMark     saas/paas标识枚举
     * @param businessType 业务类型
     * @param explainList  字段解释列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-25 20:45
     * @version
     * @since
     */
    private void triggerFieldList(SmartSettingsGetVO getVO, Integer saasMark, Integer businessType,
                                     List<FieldAttrEntity> explainList) throws XbbException {

        // 访客计划执行人：执行人&&执行人自定义人员合并为一个字段处理
        // 产品规格&&库存合并为一个字段处理（列表页暂未支持，先不处理）
        // 客户最后跟进时间（无跟进客户/遗忘客户/遗忘销售机会/无跟进供应商/遗忘供应商）
        // 待字辈：待采购、待生产、待出库、待入库
        // 合同到期筛选条件（当天，之前）
        // 销售阶段变更提醒，筛选条件（等于）
        // 采购到货筛选条件（当天，之前）
        // 生产完成筛选条件（当天，之前）
        // 应收款/付款计划（到期/逾期）
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);


        List<SmartFieldAttrPojo> smartFieldAttrPojoList = new ArrayList<>();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            // 过虑不展示字段
            if (!ShowTypeEnum.listShow(fieldAttrEntity.getShowType())) {
                continue;
            }
            // 字段回收站处理
            if (Objects.equals(fieldAttrEntity.getIsOpen(), 2)) {
                continue;
            }
            // paas过虑
            if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
                if (paasFieldFilter(fieldAttrEntity.getFieldType())) {
                    continue;
                }
            } else if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
                if (Objects.equals(XbbRefTypeEnum.COMMUNICATE_PLAN, refTypeEnum) && communicatePlanFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.PRODUCT, refTypeEnum) && productFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.CONTRACT, refTypeEnum) && contractFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT, refTypeEnum) && customerFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY, refTypeEnum) && opportunityFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.SUPPLIER, refTypeEnum) && supplierFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.PURCHASE, refTypeEnum) && purchaseFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if (Objects.equals(XbbRefTypeEnum.PRODUCTION_ORDER, refTypeEnum) && productionOrderFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if(Objects.equals(XbbRefTypeEnum.PAYMENT, refTypeEnum) && paymentFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                if(Objects.equals(XbbRefTypeEnum.PAY_PLAN, refTypeEnum) && payPlanFieldFilter(fieldAttrEntity.getSaasAttr())) {
                    continue;
                }
                // saas过虑
                if (saasFieldFilter(fieldAttrEntity.getFieldType(), fieldAttrEntity.getSaasAttr(), businessType)) {
                    continue;
                }
            }

            SmartFieldAttrPojo smartFieldAttrPojo = new SmartFieldAttrPojo();
            BeanUtil.copyProperties(fieldAttrEntity, smartFieldAttrPojo);
            smartFieldAttrPojoList.add(smartFieldAttrPojo);
        }

        // 添加：访客计划-执行人、产品-库存预警下限&产品临期、客户-无跟进客户&遗忘客户、机会-遗忘机会、供应商-无跟进供应商&遗忘供应商、
        // 合同-待采购&待生产&待入库、采购合同-待出库
        switch (refTypeEnum) {
            case COMMUNICATE_PLAN:
                addCommunicatePlanField(smartFieldAttrPojoList);
                break;
            case PRODUCT:
                addProductField(smartFieldAttrPojoList);
                break;
            case CUSTOMER_MANAGEMENT:
                addCustomerField(smartFieldAttrPojoList);
                break;
            case SALES_OPPORTUNITY:
                addOpportunityField(smartFieldAttrPojoList);
                break;
            case SUPPLIER:
                addSupplierField(smartFieldAttrPojoList);
                break;
            case CONTRACT:
                addContractField(smartFieldAttrPojoList);
                break;
            case PURCHASE:
                addPurchaseField(smartFieldAttrPojoList);
                break;
            case PRODUCTION_ORDER:
                addProductionOrderField(smartFieldAttrPojoList);
                break;
            case PAYMENT:
                addPaymentField(smartFieldAttrPojoList);
                break;
            case PAY_PLAN:
                addPayPlanField(smartFieldAttrPojoList);
                break;
            default:
                break;
        }

        getVO.setFieldAttrArray(smartFieldAttrPojoList);
    }

    /**
     * 设置字段的可选项
     *
     * @param getVO        前端需要数据
     * @param saasMark     saas/paas标识枚举
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-25 20:45
     * @version v1.0
     * @since v1.0
     */
    private void fieldConditionList(SmartSettingsGetVO getVO, Integer saasMark) throws XbbException {
        ConditionListDTO conditionListDTO = new ConditionListDTO();
        ConditionListVO conditionListVO = conditionService.list(conditionListDTO);

        Map<String, List<ConditionClass>> conditionMap = conditionListVO.getConditionList();
        List<String> dateTypeList = Arrays.asList(FieldTypeEnum.DATETIME.getType().toString(), FieldTypeEnum.ADDTIME.getType().toString(),
                FieldTypeEnum.UPDATETIME.getType().toString(), FieldTypeEnum.BIRTHDAY.getType().toString());

        // 提交时间/修改时间/期日/生日
        conditionMap.forEach((fieldType, conditionList) -> {
            if (dateTypeList.contains(fieldType)) {
                List<ConditionClass> newConditionList = getDateConditionList(fieldType);
                conditionMap.put(fieldType, newConditionList);
            }
        });

        // saas特殊字段可选条件：执行人、音频（为空/不为空）、最后跟进时间（无跟进/遗忘）产品预警（到达上限或下限、过期时间）、
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            // 执行人、音频
            List<ConditionClass> managerConditionList = ConditionEnum.getConditionList(ConditionConstant.COUSERID);
            List<ConditionClass> videoConditionList = ConditionEnum.getConditionList(ConditionConstant.UPLOAD);
            conditionMap.put(SmartSettingsFieldEnum.COMMUNICATE_PLAN_EXECUTOR.getType().toString(), managerConditionList);
            conditionMap.put(FieldTypeEnum.VIDEO.getType().toString(), videoConditionList);

            // 无跟进：客户、供应商
            List<ConditionClass> cusNoConnectConditionList = getNoConnectCondition();
            List<ConditionClass> supNoConnectConditionList = getNoConnectCondition();
            conditionMap.put(SmartSettingsFieldEnum.NO_CONNECT_CUSTOMER.getType().toString(), cusNoConnectConditionList);
            conditionMap.put(SmartSettingsFieldEnum.NO_CONNECT_SUPPLIER.getType().toString(), supNoConnectConditionList);
            // 遗忘：客户、机会、供应商
            List<ConditionClass> cusForgetConditionList = getForgetCondition();
            List<ConditionClass> oppForgetConditionList = getForgetCondition();
            List<ConditionClass> supForgetConditionList = getForgetCondition();
            conditionMap.put(SmartSettingsFieldEnum.FORGET_CUSTOMER.getType().toString(), cusForgetConditionList);
            conditionMap.put(SmartSettingsFieldEnum.FORGET_OPPORTUNITY.getType().toString(), oppForgetConditionList);
            conditionMap.put(SmartSettingsFieldEnum.FORGET_SUPPLIER.getType().toString(), supForgetConditionList);
            // 待字辈：待采购、待生产、待入库、待出库
            List<ConditionClass> purWaitConditionList = getWaitConditionList();
            List<ConditionClass> proOrderWaitConditionList = getWaitConditionList();
            List<ConditionClass> intstockWaitConditionList = getWaitConditionList();
            List<ConditionClass> outstockWaitConditionList = getWaitConditionList();
            conditionMap.put(SmartSettingsFieldEnum.WAIT_PURCHASE.getType().toString(), purWaitConditionList);
            conditionMap.put(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getType().toString(), proOrderWaitConditionList);
            conditionMap.put(SmartSettingsFieldEnum.WAIT_INSTOCK.getType().toString(), intstockWaitConditionList);
            conditionMap.put(SmartSettingsFieldEnum.WAIT_OUTSTOCK.getType().toString(), outstockWaitConditionList);
            // 产品：库存预警下限、库存预警上限、产品保质期预警
            List<ConditionClass> proStockLowerConditionList = getNoConnectCondition();
            conditionMap.put(SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getType().toString(), proStockLowerConditionList);
            List<ConditionClass> proStockUpperConditionList = getNoConnectCondition();
            conditionMap.put(SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getType().toString(), proStockUpperConditionList);
            List<ConditionClass> expireConditonList = getExpireCondtion();
            conditionMap.put(SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getType().toString(), expireConditonList);
            // 合同到期、销售阶段、采购到货、生产完成
            List<ConditionClass> contractDeadLineConditionList = getSmartDateConditonList();
            conditionMap.put(SmartSettingsFieldEnum.CONTRACT_DEAD_LINE.getType().toString(), contractDeadLineConditionList);
            List<ConditionClass> opportunityStageConditionList = getEqualConditionList();
            conditionMap.put(SmartSettingsFieldEnum.OPPORTUNITY_STAGE.getType().toString(), opportunityStageConditionList);
            List<ConditionClass> purchaseArriveTimeConditionList = getSmartDateConditonList();
            conditionMap.put(SmartSettingsFieldEnum.PURCHASE_ARRIVE_TIME.getType().toString(), purchaseArriveTimeConditionList);
            List<ConditionClass> productionOrderPlanTimeConditionList = getSmartDateConditonList();
            conditionMap.put(SmartSettingsFieldEnum.PRODUCTION_ORDER_PLAN_TIME.getType().toString(), productionOrderPlanTimeConditionList);
            // 回款到期、回款逾期、付款到期、付款逾期
            List<ConditionClass> paymentDeadLineConditionList = getPaymentOrPayPlanConditionList(false);
            conditionMap.put(SmartSettingsFieldEnum.PAYMENT_DEAD_LINE.getType().toString(), paymentDeadLineConditionList);
            List<ConditionClass> paymentOverdueConditionList = getPaymentOrPayPlanConditionList(true);
            conditionMap.put(SmartSettingsFieldEnum.PAYMENT_OVERDUE.getType().toString(), paymentOverdueConditionList);
            List<ConditionClass> payPlanDeadLineConditionList = getPaymentOrPayPlanConditionList(false);
            conditionMap.put(SmartSettingsFieldEnum.PAY_PLAN_DEAD_LINE.getType().toString(), payPlanDeadLineConditionList);
            List<ConditionClass> payPlanOverdueConditionList = getPaymentOrPayPlanConditionList(true);
            conditionMap.put(SmartSettingsFieldEnum.PAY_PLAN_OVERDUE.getType().toString(), payPlanOverdueConditionList);
        }

        getVO.setFieldConditionArray(conditionMap);
    }

    /**
     * 获取执行人可选项
     *
     * @param getVO        前端需要数据
     * @param saasMark     saas/paas标识枚举
     * @param businessType 业务类型
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-20 20:58
     * @version v1.0
     * @since v1.0
     */
    private void dynamicManagerList(SmartSettingsGetVO getVO, Integer saasMark, Integer businessType) {
        List<ReturnExplainPojo> resultList = new ArrayList<>();

        // 负责人、协同人
        ReturnExplainPojo ownerPojo = new ReturnExplainPojo();
        ownerPojo.setAttr(FieldTypeEnum.OWNERID.getAlias());
        ownerPojo.setName(I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID));
        resultList.add(ownerPojo);

        if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
            ReturnExplainPojo coUserPojo = new ReturnExplainPojo();
            coUserPojo.setAttr(FieldTypeEnum.COUSERID.getAlias());
            coUserPojo.setName(I18nMessageUtil.getMessage(DynamicManagerConstant.COUSERID));
            resultList.add(coUserPojo);
        }

        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            ReturnExplainPojo linkPojo = new ReturnExplainPojo();
            switch (xbbRefTypeEnum) {
                // 回款到期/逾期
                case PAYMENT:
                    // 关联合同负责人
                    linkPojo.setAttr(DynamicManagerConstant.LINK_CONTRACT_ALIAS);
                    linkPojo.setName(I18nMessageUtil.getMessage(DynamicManagerConstant.LINK_CONTRACT_NAME));
                    resultList.add(linkPojo);
                    break;
                // 采购到货/新采购合同/待入库未处理、生产完成、产品库存预警/产品到期预警、待出库未处理（合同）
//                case PURCHASE:
//                case PRODUCTION_ORDER:
//                case PRODUCT:
//                case CONTRACT:
//                    // 关联仓库负责人
//                    linkPojo.setAttr(DynamicManagerConstant.LINK_WARE_HOUSE_ALIAS);
//                    linkPojo.setName(DynamicManagerConstant.LINK_WARE_HOUSE_NAME);
//                    resultList.add(linkPojo);
//                    break;
                case WORK_REPORT:
                    resultList.clear();
                    break;
                // 付款到期/逾期
                case PAY_PLAN:
                    // 关联采购合同负责人
                    linkPojo.setAttr(DynamicManagerConstant.LINK_PURCHASE_ALIAS);
                    linkPojo.setName(I18nMessageUtil.getMessage(DynamicManagerConstant.LINK_PURCHASE_NAME));
                    resultList.add(linkPojo);
                    break;
                default:
                    break;
            }
        }

        getVO.setDynamicManagerArray(resultList);
    }

    /**
     * 获取paas可作为执行人的字段
     *
     * @param getVO        前端需要数据
     * @param saasMark     saas/paas标识枚举
     * @param businessType 业务类型
     * @param explainList  字段解释列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-06-24 15:28
     * @version v1.0
     * @since v1.0
     */
    private void smsExecutorList(SmartSettingsGetVO getVO, Integer saasMark, Integer businessType, List<FieldAttrEntity> explainList) {
        List<SmartFieldAttrPojo> smsExecutorArray = new ArrayList<>();
        if (Objects.equals(SaasMarkEnum.PAAS.getCode(), saasMark)) {
            for (FieldAttrEntity entity : explainList) {
                // 单行文本&&手机号
                if (Objects.equals(FieldTypeEnum.TEXT.getType(), entity.getFieldType()) && Objects.equals(PatternEnum.MOBILE.getType(), entity.getPatternType())) {
                    SmartFieldAttrPojo smartFieldAttrPojo = new SmartFieldAttrPojo();
                    BeanUtil.copyProperties(entity, smartFieldAttrPojo);
                    smsExecutorArray.add(smartFieldAttrPojo);
                }
            }
        }
        getVO.setSmsExecutorArray(smsExecutorArray);
    }

    /**
     * paas字段过虑
     *
     * @param fieldType 字段类型
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-26 10:12
     * @version v1.0
     * @since v1.0
     */
    private boolean paasFieldFilter(Integer fieldType) {
        // 可用字段：单行文本、单选按钮、下拉框、复选框、下拉复选框、成员多选/部门多选、成员单选/部门单选、多行文本、数字、
        //          提交人、提交时间/修改时间、日期、提交人所属部门
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        boolean isFilter = true;
        switch (fieldTypeEnum) {
            case TEXT:
            case RADIO_GROUP:
            case COMBO:
            case CHECKBOX_GROUP:
            case COMBO_CHECK:
            case USER_GROUP:
            case DEPT_GROUP:
            case USER:
            case DEPT:
            case TEXTAREA:
            case NUM:
            case CREATORID:
            case ADDTIME:
            case UPDATETIME:
            case DATETIME:
            case DEPARTMENTID:
            case STAGE_THRUSTER:
                isFilter = false;
                break;
            default:
                break;
        }

        return isFilter;
    }

    /**
     * saas字段过滤
     *
     * @param fieldType    字段类型
     * @param saasAttr     saas字段别名
     * @param businessType 业务类型
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-26 13:50
     * @version v1.0
     * @since v1.0
     */
    private boolean saasFieldFilter(Integer fieldType, String saasAttr, Integer businessType) {
        // 可用字段：与paas同（除“提交人所属部门”）&& saas特殊字段处理
        boolean isFilter = paasFieldFilter(fieldType);

        if (!isFilter) {
            if (fieldType.equals(FieldTypeEnum.DEPARTMENTID.getType())) {
                isFilter = true;
            }
        } else {
            // saas特殊字段处理:关联业务单选（关联客户）、联系电话、选择产品、勾选+下拉选择（执行人）--暂时不添加（2019.8.19）、规格(库存)、富文本编辑器、生日、星级、音频
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
            switch (fieldTypeEnum) {
                case LINK_BUSINESS_SINGLE:
                    isFilter = notLinkCustomer(saasAttr, businessType);
                    break;
                // 联系人是子表单，以后再处理
                // case CONTACT_NUMBER:
                case SELECT_PRODUCT:
//                case CHECK_COMBO:
                case SPECIFICATION:
                case RICH_TEXT_EDITOR:
                case BIRTHDAY:
                case STAR:
                case VIDEO:
                case STAGE_THRUSTER:
                    isFilter = false;
                    break;
                default:
                    break;
            }
        }

        return isFilter;
    }

    /**
     * 是否为关联客户
     *
     * @param saasAttr     saas字段别名
     * @param businessType 业务类型
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-26 15:17
     * @version v1.0
     * @since v1.0
     */
    private boolean notLinkCustomer(String saasAttr, Integer businessType) {
        // 关联客户的表单：联系人、跟进记录、访客计划、销售机会、合同订单、应收款、发票管理
        boolean isCustomer = true;
        XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (refTypeEnum) {
            case CONTACT:
                isCustomer = ContactEnum.CUSTOMER_NAME.getSaasAttr().equals(saasAttr);
                break;
            case CUSTOMER_COMMUNICATE:
                isCustomer = CustomerCommunicateEnum.CUSTOMER_NAME.getSaasAttr().equals(saasAttr);
                break;
            case COMMUNICATE_PLAN:
                isCustomer = CommunicatePlanEnum.LINK_CUSTOMER.getSaasAttr().equals(saasAttr);
                break;
            case SALES_OPPORTUNITY:
                isCustomer = SalesOpportunityEnum.CUSTOMER_NAME.getSaasAttr().equals(saasAttr) || SalesOpportunityEnum.WIN_COMPETITOR.getSaasAttr().equals(saasAttr);
                break;
            case CONTRACT:
                isCustomer = ContractEnum.LINK_CUSTOMER.getSaasAttr().equals(saasAttr);
                break;
            case PAYMENT:
                isCustomer = PaymentEnum.CUSTOMER.getSaasAttr().equals(saasAttr);
                break;
            case INVOICE:
                isCustomer = InvoiceEnum.CUSTOMER_NAME.getSaasAttr().equals(saasAttr);
                break;
            default:
                break;
        }

        return !isCustomer;
    }

    /**
     * 访客计划字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:33
     * @version v1.0
     * @since v1.0
     */
    private boolean communicatePlanFieldFilter(String saasAttr) {
        return Objects.equals(CommunicatePlanEnum.EXECUTOR.getSaasAttr(), saasAttr) ||
                Objects.equals(CommunicatePlanEnum.EXECUTOR_LINKED_TEXT.getSaasAttr(), saasAttr);
    }

    /**
     * 产品字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:33
     * @version v1.0
     * @since v1.0
     */
    private boolean productFieldFilter(String saasAttr) {
        return Objects.equals(ProductEnum.STOCK.getSaasAttr(), saasAttr);
    }

    /**
     * 合同字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-28 09:04
     * @version v1.0
     * @since v1.0
     */
    private boolean contractFieldFilter(String saasAttr) {
        return Objects.equals(ContractEnum.DEADLINE.getSaasAttr(), saasAttr);
    }

    private boolean customerFieldFilter(String saasAttr) {
        return Objects.equals(CustomerManagementEnum.LAST_CONNECT_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 机会字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-28 09:05
     * @version v1.0
     * @since v1.0
     */
    private boolean opportunityFieldFilter(String saasAttr) {
        return Objects.equals(SalesOpportunityEnum.SALE_STAGE.getSaasAttr(), saasAttr)
                || Objects.equals(SalesOpportunityEnum.LAST_CONNECT_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 供应商字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-07-23 09:45
     * @version v1.0
     * @since v1.0
     */
    private boolean supplierFieldFilter(String saasAttr) {
        return Objects.equals(SupplierEnum.LAST_CONNECT_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 采购合同字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-28 09:06
     * @version v1.0
     * @since v1.0
     */
    private boolean purchaseFieldFilter(String saasAttr) {
        return Objects.equals(PurchaseEnum.ESTIMATE_ARRIVE_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 生产单字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-28 09:08
     * @version v1.0
     * @since v1.0
     */
    private boolean productionOrderFieldFilter(String saasAttr) {
        return Objects.equals(ProductionOrderEnum.PLAN_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 应收款字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-24 19:03
     * @since v1.0
     * @version v1.0
     */
    private boolean paymentFieldFilter(String saasAttr) {
        return Objects.equals(PaymentEnum.ESTIMATE_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 付款计划字段过虑
     *
     * @param saasAttr saas字段别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-24 19:03
     * @since v1.0
     * @version v1.0
     */
    private boolean payPlanFieldFilter(String saasAttr) {
        return Objects.equals(PayPlanEnum.ESTIMATE_TIME.getSaasAttr(), saasAttr);
    }

    /**
     * 访客计划：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:34
     * @version v1.0
     * @since v1.0
     */
    private void addCommunicatePlanField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 执行人
        SmartFieldAttrPojo pojo = new SmartFieldAttrPojo();
        pojo.setAttr(SmartSettingsFieldEnum.COMMUNICATE_PLAN_EXECUTOR.getAlias());
        pojo.setAttrName(SmartSettingsFieldEnum.COMMUNICATE_PLAN_EXECUTOR.getDescription());
        pojo.setFieldType(SmartSettingsFieldEnum.COMMUNICATE_PLAN_EXECUTOR.getType());
        smartFieldAttrPojoList.add(pojo);
    }

    /**
     * 产品：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:35
     * @version v1.0
     * @since v1.0
     */
    private void addProductField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 库存预警下限、上限、产品保质期
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getType());
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getType());
        SmartFieldAttrPojo pojo3 = new SmartFieldAttrPojo();
        pojo3.setAttr(SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getAlias());
        pojo3.setAttrName(SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getDescription());
        pojo3.setFieldType(SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getType());

        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
        smartFieldAttrPojoList.add(pojo3);
    }

    /**
     * 客户：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:35
     * @version v1.0
     * @since v1.0
     */
    private void addCustomerField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 无跟进客户、遗忘客户
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.NO_CONNECT_CUSTOMER.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.NO_CONNECT_CUSTOMER.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.NO_CONNECT_CUSTOMER.getType());
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.FORGET_CUSTOMER.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.FORGET_CUSTOMER.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.FORGET_CUSTOMER.getType());

        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
    }

    /**
     * 机会：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:35
     * @version v1.0
     * @since v1.0
     */
    private void addOpportunityField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 遗忘机会
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.FORGET_OPPORTUNITY.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.FORGET_OPPORTUNITY.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.FORGET_OPPORTUNITY.getType());
        // 销售阶段
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.OPPORTUNITY_STAGE.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.OPPORTUNITY_STAGE.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.OPPORTUNITY_STAGE.getType());

        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
    }

    /**
     * 供应商：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:35
     * @version v1.0
     * @since v1.0
     */
    private void addSupplierField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 无跟进供应商、遗忘供应商
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.NO_CONNECT_SUPPLIER.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.NO_CONNECT_SUPPLIER.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.NO_CONNECT_SUPPLIER.getType());
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.FORGET_SUPPLIER.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.FORGET_SUPPLIER.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.FORGET_SUPPLIER.getType());

        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
    }

    /**
     * 合同：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:35
     * @version v1.0
     * @since v1.0
     */
    private void addContractField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 待采购、待生产、待出库
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.WAIT_PURCHASE.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.WAIT_PURCHASE.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.WAIT_PURCHASE.getType());
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getType());
        SmartFieldAttrPojo pojo3 = new SmartFieldAttrPojo();
        pojo3.setAttr(SmartSettingsFieldEnum.WAIT_OUTSTOCK.getAlias());
        pojo3.setAttrName(SmartSettingsFieldEnum.WAIT_OUTSTOCK.getDescription());
        pojo3.setFieldType(SmartSettingsFieldEnum.WAIT_OUTSTOCK.getType());
        // 合同到期
        SmartFieldAttrPojo pojo4 = new SmartFieldAttrPojo();
        pojo4.setAttr(SmartSettingsFieldEnum.CONTRACT_DEAD_LINE.getAlias());
        pojo4.setAttrName(SmartSettingsFieldEnum.CONTRACT_DEAD_LINE.getDescription());
        pojo4.setFieldType(SmartSettingsFieldEnum.CONTRACT_DEAD_LINE.getType());

        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
        smartFieldAttrPojoList.add(pojo3);
        smartFieldAttrPojoList.add(pojo4);
    }

    /**
     * 采购合同：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:35
     * @version v1.0
     * @since v1.0
     */
    private void addPurchaseField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 待入库
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.WAIT_INSTOCK.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.WAIT_INSTOCK.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.WAIT_INSTOCK.getType());
        // 采购到货
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.PURCHASE_ARRIVE_TIME.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.PURCHASE_ARRIVE_TIME.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.PURCHASE_ARRIVE_TIME.getType());
        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
    }

    /**
     * 生产单：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-28 09:02
     * @version v1.0
     * @since v1.0
     */
    private void addProductionOrderField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.PRODUCTION_ORDER_PLAN_TIME.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.PRODUCTION_ORDER_PLAN_TIME.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.PRODUCTION_ORDER_PLAN_TIME.getType());
        smartFieldAttrPojoList.add(pojo1);
    }

    /**
     * 应收款：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-24 19:08
     * @since v1.0
     * @version v1.0
     */
    private void addPaymentField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 回款到期
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.PAYMENT_DEAD_LINE.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.PAYMENT_DEAD_LINE.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.PAYMENT_DEAD_LINE.getType());
        // 回款逾期
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.PAYMENT_OVERDUE.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.PAYMENT_OVERDUE.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.PAYMENT_OVERDUE.getType());
        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
    }

    /**
     * 付款计划：添加触发字段
     *
     * @param smartFieldAttrPojoList 字段列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-24 19:08
     * @since v1.0
     * @version v1.0
     */
    private void addPayPlanField(List<SmartFieldAttrPojo> smartFieldAttrPojoList) {
        // 付款到期
        SmartFieldAttrPojo pojo1 = new SmartFieldAttrPojo();
        pojo1.setAttr(SmartSettingsFieldEnum.PAY_PLAN_DEAD_LINE.getAlias());
        pojo1.setAttrName(SmartSettingsFieldEnum.PAY_PLAN_DEAD_LINE.getDescription());
        pojo1.setFieldType(SmartSettingsFieldEnum.PAY_PLAN_DEAD_LINE.getType());
        // 付款逾期
        SmartFieldAttrPojo pojo2 = new SmartFieldAttrPojo();
        pojo2.setAttr(SmartSettingsFieldEnum.PAY_PLAN_OVERDUE.getAlias());
        pojo2.setAttrName(SmartSettingsFieldEnum.PAY_PLAN_OVERDUE.getDescription());
        pojo2.setFieldType(SmartSettingsFieldEnum.PAY_PLAN_OVERDUE.getType());
        smartFieldAttrPojoList.add(pojo1);
        smartFieldAttrPojoList.add(pojo2);
    }

    /**
     * 获取提交时间/修改时间/期日可选项
     *
     * @param fieldType 字段类型
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-27 14:14
     * @version v1.0
     * @since v1.0
     */
    private List<ConditionClass> getDateConditionList(String fieldType) {
        // 当天，之后，之前（日期）
        List<ConditionClass> list = new ArrayList<>();
        ConditionClass nowClass = new ConditionClass();
        ConditionClass afterClass = new ConditionClass();
        ConditionClass beforeClass = new ConditionClass();
        BeanUtil.copyProperties(SmartSettingsConditionEnum.NOW, nowClass);
        BeanUtil.copyProperties(SmartSettingsConditionEnum.AFTER, afterClass);
        BeanUtil.copyProperties(SmartSettingsConditionEnum.BEFORE, beforeClass);

        if (Objects.equals(FieldTypeEnum.ADDTIME.getType().toString(), fieldType)
                || Objects.equals(FieldTypeEnum.UPDATETIME.getType().toString(), fieldType)) {
            list.add(afterClass);
        } else if (Objects.equals(FieldTypeEnum.DATETIME.getType().toString(), fieldType)) {
            list.add(nowClass);
            list.add(afterClass);
            list.add(beforeClass);
        } else if (Objects.equals(FieldTypeEnum.BIRTHDAY.getType().toString(), fieldType)) {
            list.add(nowClass);
            list.add(beforeClass);
        }
        return list;
    }

    /**
     * 未跟进的可选条件
     *
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 17:15
     * @version v1.0
     * @since v1.0
     */
    private List<ConditionClass> getNoConnectCondition() {
        // 符合条件
        ConditionClass conditionClass = new ConditionClass();
        BeanUtil.copyProperties(SmartSettingsConditionEnum.EQUAL_CONDITION, conditionClass);
        return Collections.singletonList(conditionClass);
    }

    /**
     * 遗忘提醒的可选条件
     *
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 17:15
     * @version v1.0
     * @since v1.0
     */
    private List<ConditionClass> getForgetCondition() {
        // 大于、小于、大于等于、小于等于、选择范围
        String[] forgetConditionTxt = {ConditionEnum.GREATERTHAN.getSymbol(), ConditionEnum.GREATEREQUAL.getSymbol(),
                ConditionEnum.LESSTHAN.getSymbol(),ConditionEnum.LESSEQUAL.getSymbol(), ConditionEnum.RANGE.getSymbol()};
        return ConditionEnum.getConditionList(forgetConditionTxt);
    }

    /**
     * 待字辈（待XX未处理）的可选条件
     *
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:31
     * @version v1.0
     * @since v1.0
     */
    private List<ConditionClass> getWaitConditionList() {
        // 大于、小于、大于等于、小于等于、选择范围
        return getForgetCondition();
    }

    /**
     * 过期的可选条件
     *
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-28 19:25
     * @version v1.0
     * @since v1.0
     */
    private List<ConditionClass> getExpireCondtion() {
        // 选择范围
        String[] conditionTxt = {ConditionEnum.RANGE.getSymbol()};
        return ConditionEnum.getConditionList(conditionTxt);
    }

    /**
     * 获取特殊时间字段条件可选项
     *
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-05-28 09:01
     * @version v1.0
     * @since v1.0
     */
    private List<ConditionClass> getSmartDateConditonList() {
        List<ConditionClass> list = new ArrayList<>();
        ConditionClass nowClass = new ConditionClass();
        ConditionClass beforeClass = new ConditionClass();
        BeanUtil.copyProperties(SmartSettingsConditionEnum.NOW, nowClass);
        BeanUtil.copyProperties(SmartSettingsConditionEnum.BEFORE, beforeClass);

        list.add(nowClass);
        list.add(beforeClass);

        return list;
    }

    /**
     * 获取应收款/付款计划：预计回款时间字段条件可选项
     *
     * @param
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-24 19:16
     * @since
     * @version
     */
    private List<ConditionClass> getPaymentOrPayPlanConditionList(boolean overdueFla) {
        List<ConditionClass> list = new ArrayList<>();
        ConditionClass nowClass = new ConditionClass();
        ConditionClass beforeClass = new ConditionClass();
        ConditionClass afterClass = new ConditionClass();
        BeanUtil.copyProperties(SmartSettingsConditionEnum.NOW, nowClass);
        BeanUtil.copyProperties(SmartSettingsConditionEnum.BEFORE, beforeClass);
        BeanUtil.copyProperties(SmartSettingsConditionEnum.AFTER, afterClass);
        // 逾期（之后）
        if(overdueFla) {
            list.add(afterClass);
        } else {
            // 到期（之前，当天）
            list.add(beforeClass);
            list.add(nowClass);
        }

        return list;
    }

    /**
     * 获取等于条件
     *
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-12-26 17:23
     * @since v4.9.0
     * @version v4.9.0
     */
    private List<ConditionClass> getEqualConditionList() {
        String[] conditionTxt = {ConditionEnum.EQUAL.getSymbol()};
        return ConditionEnum.getConditionList(conditionTxt);
    }

    /**
     * 过虑应用菜单
     *
     * @param alias 应用别名
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-06-27 16:10
     * @version v1.0
     * @since v1.0
     */
    private boolean filterApp(String alias) {
        if (StringUtil.isEmpty(alias)) {
            return false;
        }
        // crm应用
        List<String> crmAliasList = getCrmAliasList();
        // jxc应用
        List<String> jxcAliasList = getJxcAliasList();
        // 资金管理
        List<String> fundAliasList = getFundAliasList();
        // 产品
        List<String> productList = getProductAliasList();
        //市场管理
        List<String> marketManagementList = getMarketManagementAliasList();
        if (crmAliasList.contains(alias) || jxcAliasList.contains(alias) || fundAliasList.contains(alias) || productList.contains(alias) || marketManagementList.contains(alias)) {
            return false;
        }
        return true;
    }

    /**
     * crm业务表单的alias
     */
    private List<String> getCrmAliasList() {
        return Arrays.asList(XbbRefTypeEnum.CRM.getAlias(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias(),
                XbbRefTypeEnum.CONTACT.getAlias(), XbbRefTypeEnum.CONTRACT.getAlias(), XbbRefTypeEnum.SALES_OPPORTUNITY.getAlias(),
                XbbRefTypeEnum.WORK_REPORT.getAlias(), XbbRefTypeEnum.WORKREPORT_DAILY.getAlias(), XbbRefTypeEnum.WORKREPORT_WEEKLY.getAlias(),
                XbbRefTypeEnum.WORKREPORT_MONTHLY.getAlias(), XbbRefTypeEnum.REFUND.getAlias());
    }

    /**
     * 进销存业务表单的alias
     */
    private List<String> getJxcAliasList() {
        return Arrays.asList(XbbRefTypeEnum.JXC.getAlias(), XbbRefTypeEnum.PURCHASE_MANAGEMENT.getAlias(),
                XbbRefTypeEnum.INVENTORY_MANAGEMENT.getAlias(), XbbRefTypeEnum.PRODUCTION_MANAGEMENT.getAlias(), XbbRefTypeEnum.SUPPLIER.getAlias(),
                XbbRefTypeEnum.SUPPLIER_CONTACT.getAlias(), XbbRefTypeEnum.PURCHASE.getAlias(), XbbRefTypeEnum.RETURNED_PURCHASE.getAlias(),
                XbbRefTypeEnum.ASSEMBLE.getAlias(), XbbRefTypeEnum.TRANSFER.getAlias(),
                XbbRefTypeEnum.INVENTORY.getAlias(), XbbRefTypeEnum.BOM_BILL.getAlias(), XbbRefTypeEnum.PRODUCTION_ORDER.getAlias());
    }

    /**
     * 资金管理业务表单的alias
     */
    private List<String> getFundAliasList() {
        return Arrays.asList(XbbRefTypeEnum.FUND_MANAGEMENT.getAlias(), XbbRefTypeEnum.PAYMENT.getAlias(), XbbRefTypeEnum.PAY_PLAN.getAlias(), XbbRefTypeEnum.PAY_MANAGEMENT.getAlias(), XbbRefTypeEnum.PAYMENT_MANAGEMENT.getAlias(),
                XbbRefTypeEnum.INVOICE.getAlias());
    }

    /**
     * 产品业务表单的alias
     */
    private List<String> getProductAliasList() {
        return Arrays.asList(XbbRefTypeEnum.PRODUCT.getAlias());
    }

    /**
     * 市场管理业务表单的alias
     */
    private List<String> getMarketManagementAliasList() {
        return Arrays.asList(XbbRefTypeEnum.MARKET_ACTIVITY.getAlias(),XbbRefTypeEnum.CLUE.getAlias());
    }

    /**
     * crm业务表单的code
     */
    private List<Integer> getCrmCodeList() {
        return Arrays.asList(XbbRefTypeEnum.CRM.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),
                XbbRefTypeEnum.CONTACT.getCode(), XbbRefTypeEnum.CONTRACT.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(),
                XbbRefTypeEnum.WORK_REPORT.getCode(), XbbRefTypeEnum.WORKREPORT_DAILY.getCode(), XbbRefTypeEnum.WORKREPORT_WEEKLY.getCode(),
                XbbRefTypeEnum.WORKREPORT_MONTHLY.getCode(), XbbRefTypeEnum.REFUND.getCode());
    }

    /**
     * 进销存业务表单的code
     */
    private List<Integer> getJxcCodeList() {
        return Arrays.asList(XbbRefTypeEnum.JXC.getCode(), XbbRefTypeEnum.PURCHASE_MANAGEMENT.getCode(),
                XbbRefTypeEnum.INVENTORY_MANAGEMENT.getCode(), XbbRefTypeEnum.PRODUCTION_MANAGEMENT.getCode(), XbbRefTypeEnum.SUPPLIER.getCode(),
                XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), XbbRefTypeEnum.PURCHASE.getCode(), XbbRefTypeEnum.RETURNED_PURCHASE.getCode(),
                XbbRefTypeEnum.ASSEMBLE.getCode(), XbbRefTypeEnum.INSTOCK.getCode(), XbbRefTypeEnum.OUTSTOCK.getCode(), XbbRefTypeEnum.TRANSFER.getCode(),
                XbbRefTypeEnum.INVENTORY.getCode(), XbbRefTypeEnum.BOM_BILL.getCode(), XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
    }

    /**
     * 资金管理业务表单的code
     */
    private List<Integer> getFundCodeList() {
        return Arrays.asList(XbbRefTypeEnum.FUND_MANAGEMENT.getCode(), XbbRefTypeEnum.PAYMENT.getCode(), XbbRefTypeEnum.PAY_PLAN.getCode(),
                XbbRefTypeEnum.INVOICE.getCode());
    }

    /**
     * 产品业务表单的code
     */
    private List<Integer> getProductCodeList() {
        return Arrays.asList(XbbRefTypeEnum.PRODUCT.getCode());
    }

    /**
     * 设置saas/paas智能助手信息（名称，启用数/总数）
     *
     * @param entity    智能助手实体
     * @param formIdSet 表单ids
     * @param menuIdSet paas菜单ids
     * @param saasMap   saas{businessType: businessPojo}
     * @param paasMap   paas{menuId: businessPojo}
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-21 09:07
     * @version v1.0
     * @since v1.0
     */
    private void setBusinessListPojo(AiAssistantEntity entity, Set<Long> formIdSet, Set<Long> menuIdSet,
                                     Map<Long, SmartSettingsBusinessListPojo> saasMap, Map<Long, SmartSettingsBusinessListPojo> paasMap) {
        Integer saasMark = entity.getSaasMark();
        Integer enable = entity.getEnable();
        Long menuId = entity.getMenuId();
        Integer businessType = entity.getBusinessType();
        formIdSet.add(entity.getFormId());

        if (SaasMarkEnum.PAAS.getCode().equals(saasMark)) {
            // paas菜单id
            menuIdSet.add(menuId);
            // 计算启用个数及总数
            setSsCountMap(paasMap, saasMark, menuId, null, menuId, enable, null);
        } else if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
            XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            if (refTypeEnum == XbbRefTypeEnum.UNKNOWN) {
                return;
            }
            // 计算启用个数及总数
            setSsCountMap(saasMap, saasMark, businessType.longValue(), businessType, null, enable, refTypeEnum.getName());
        }
    }

    /**
     * 设置启用的个数及总数
     *
     * @param map          设置的数据
     * @param saasMark     saas/paas标识
     * @param businessType saas业务类型
     * @param menuId       菜单id
     * @param key          数据的键
     * @param enable       是否启用（0未启，1启用）
     * @param name         名称
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-07-30 21:50
     * @version v1.0
     * @since v1.0
     */
    private void setSsCountMap(Map<Long, SmartSettingsBusinessListPojo> map, Integer saasMark, Long key, Integer businessType, Long menuId, Integer enable, String name) {

        if (map.containsKey(key)) {
            SmartSettingsBusinessListPojo businessListPojo = map.get(key);
            Integer totalCount = businessListPojo.getTotalCount() + 1;
            Integer enableCount = businessListPojo.getEnableCount() + enable;
            businessListPojo.setTotalCount(totalCount);
            businessListPojo.setEnableCount(enableCount);
        } else {
            SmartSettingsBusinessListPojo businessListPojo = new SmartSettingsBusinessListPojo();
            // 总数/启用数
            businessListPojo.setTotalCount(1);
            businessListPojo.setEnableCount(enable);
            // saas/paas标识
            businessListPojo.setSaasMark(saasMark);
            // businessType、saas名称、paas的menuId
            if (Objects.nonNull(businessType)) {
                businessListPojo.setBusinessType(businessType);
            }
            if (Objects.nonNull(menuId)) {
                businessListPojo.setMenuId(menuId);
            }
            if (Objects.nonNull(name)) {
                businessListPojo.setName(name);
            }
            map.put(key, businessListPojo);
        }
    }

    /**
     * 初始化crm智能助手
     *
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-20 16:23
     * @version v1.0
     * @since v1.0
     */
    private void initSmartSettingsForCrm(String corpid) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        int count = aiAssistantModel.getEntitysCount(param);
        if (count > 0) {
            return;
        }
        // CRM未启用不初始化
        PaasAppEntity jxcAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.CRM.getAlias(), corpid);
        if (Objects.isNull(jxcAppEntity) || Objects.equals(BasicConstant.NO_USE, jxcAppEntity.getEnable())) {
            return;
        }

        // 获取表单数据
        List<Integer> businessTypeList = Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CONTRACT.getCode(),
                XbbRefTypeEnum.PAYMENT.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), XbbRefTypeEnum.WORKREPORT_WEEKLY.getCode());
        param.clear();
        param.put(StringConstant.CORPID, corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("businessTypeList", businessTypeList);
        List<PaasFormEntityExt> formEntitys = paasFormModel.getByBusinessTypes(param);
        if (formEntitys.isEmpty()) {
            return;
        }

        List<AiAssistantEntity> list = new ArrayList<>();
        // 客户、合同只使用第一个表单、客户生日需要个人客户表单
        Map<Integer, PaasFormEntityExt> saasFormEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> customerFormIds = new ArrayList<>();
        for (PaasFormEntityExt formEntityExt : formEntitys) {
            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), formEntityExt.getBusinessType())) {
                customerFormIds.add(formEntityExt.getId());
            }
        }

        for (PaasFormEntityExt formEntityExt : formEntitys) {
            Integer businessType = formEntityExt.getBusinessType();
            // 客户生日需要个人客户表单
            if (!saasFormEntityMap.containsKey(businessType)) {
                saasFormEntityMap.put(businessType, formEntityExt);

                XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                if (refTypeEnum == XbbRefTypeEnum.UNKNOWN) {
                    continue;
                }

                switch (refTypeEnum) {
                    case CUSTOMER_MANAGEMENT:
                        list.addAll(initCustomerSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId(), customerFormIds));
                        break;
                    case CONTRACT:
                        list.addAll(initContractSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case PAYMENT:
                        list.addAll(initPaymentSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case SALES_OPPORTUNITY:
                        list.addAll(initOpportunitySmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case WORKREPORT_WEEKLY:
                        list.addAll(initWorkReportSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    default:
                        break;
                }
            }
        }

        try {
            aiAssistantModel.insertBatch(list);
        } catch (Exception e) {
            LOG.error("智能助手初始化数据失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

    }

    /**
     * 初始化jxc智能助手
     *
     * @param corpid 公司id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-20 16:23
     * @version v1.0
     * @since v1.0
     */
    private void initSmartSettingsForJxc(String corpid) throws XbbException {
        boolean hasJxc = aiAssistantModel.hasJxcSmart(corpid);
        if (hasJxc) {
            return;
        }
        // 进销存未启用不初始化
        PaasAppEntity jxcAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.JXC.getAlias(), corpid);
        if (Objects.isNull(jxcAppEntity) || Objects.equals(BasicConstant.NO_USE, jxcAppEntity.getEnable())) {
            return;
        }


        // 获取表单数据
        List<Integer> businessTypeList = Arrays.asList(XbbRefTypeEnum.SUPPLIER.getCode(), XbbRefTypeEnum.PURCHASE.getCode(),
                XbbRefTypeEnum.PAY_PLAN.getCode(), XbbRefTypeEnum.PRODUCTION_ORDER.getCode(), XbbRefTypeEnum.PRODUCTION_ORDER.getCode(),
                XbbRefTypeEnum.PRODUCT.getCode());
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("businessTypeList", businessTypeList);
        List<PaasFormEntityExt> formEntitys = paasFormModel.getByBusinessTypes(param);
        if (formEntitys.isEmpty()) {
            return;
        }

        List<AiAssistantEntity> list = new ArrayList<>();

        Map<Integer, PaasFormEntityExt> saasFormEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormEntityExt formEntityExt : formEntitys) {
            Integer businessType = formEntityExt.getBusinessType();
            if (!saasFormEntityMap.containsKey(businessType)) {
                saasFormEntityMap.put(businessType, formEntityExt);

                XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                if (refTypeEnum == XbbRefTypeEnum.UNKNOWN) {
                    continue;
                }
                switch (refTypeEnum) {
                    case SUPPLIER:
                        list.addAll(initSupplierSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case PURCHASE:
                        list.addAll(initPurchaseSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case PAY_PLAN:
                        list.addAll(initPayPlanSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case PRODUCTION_ORDER:
                        list.addAll(initProductionOrderSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    case PRODUCT:
                        list.addAll(initProductSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
                        break;
                    default:
                        break;
                }
            }
        }

        // 获取合同的表单
        Integer contractBusinessType = XbbRefTypeEnum.CONTRACT.getCode();
        param.put("businessTypeList", Arrays.asList(contractBusinessType));
        List<PaasFormEntityExt> contractFormList = paasFormModel.getByBusinessTypes(param);
        if (!contractFormList.isEmpty()) {
            PaasFormEntityExt formEntityExt = contractFormList.get(0);
            list.addAll(initLinkContractSmart(corpid, formEntityExt.getAppId(), formEntityExt.getId(), formEntityExt.getMenuId()));
        }

        try {
            aiAssistantModel.insertBatch(list);
        } catch (Exception e) {
            LOG.error("智能助手初始化数据失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 初始化客户智能助手
     *
     * @param corpid 公司id
     * @param appId  应用id
     * @param formId 表单id
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-20 16:01
     * @version v1.0
     * @since v1.0
     */
    private List<AiAssistantEntity> initCustomerSmart(String corpid, Long appId, Long formId, Long menuId, List<Long> formIds) throws XbbException{


        // 触发条件：添加时间、未跟进时间、最后跟进时间（大于等于7天未跟进）、客户生日（当天）
        ConditionsEntityExt addTimeCondition = new ConditionsEntityExt(CustomerManagementEnum.ADD_TIME.getAttr(), "",
                CustomerManagementEnum.ADD_TIME.getFieldType(), SmartSettingsConditionEnum.AFTER.getSymbol(), Collections.singletonList(1));

        ConditionsEntityExt noConnectCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.NO_CONNECT_CUSTOMER.getAlias(), "",
                SmartSettingsFieldEnum.NO_CONNECT_CUSTOMER.getType(), SmartSettingsConditionEnum.EQUAL_CONDITION.getSymbol(), new ArrayList<>());

        ConditionsEntityExt forgetCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.FORGET_CUSTOMER.getAlias(), "",
                SmartSettingsFieldEnum.FORGET_CUSTOMER.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        // 执行策略(每天9:00，执行3次）
        JSONObject strategyObj1 = new JSONObject();
        strategyObj1.put("strategyNum", 3);
        strategyObj1.put("strategyTime", "09:00");
        strategyObj1.put("strategyType", 2);
        strategyObj1.put("strategyCycle", 1);
        // 执行策略（09:00，执行1次）
        JSONObject strategyObj2 = new JSONObject();
        strategyObj1.put("strategyNum", 1);
        strategyObj2.put("strategyTime", "09:00");
        strategyObj2.put("strategyType", 2);
        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(), OptionalRangeEnum.DYNAMIC_MANAGER.getValue(),
                FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);

        // ================== 新增客户 =====================
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(addTimeCondition);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("新增客户");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj1);
        entity1.setExecutor(executorArr);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("新增的客户，请及时跟进！");

        // ================== 无跟进客户 =====================
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(noConnectCondition);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setEnable(BasicConstant.NO_USE);
        entity2.setName("无跟进客户");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity2.setStrategy(strategyObj2);
        entity2.setExecutor(executorArr);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("还没有跟进记录，请及时跟进！");

        // ================== 遗忘客户 =====================
        JSONArray triggerCondition3 = new JSONArray();
        triggerCondition3.add(forgetCondition);

        AiAssistantEntity entity3 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity3);
        entity3.setEnable(BasicConstant.NO_USE);
        entity3.setName("7天未跟进客户提醒");
        entity3.setTriggerCondition(triggerCondition3);
        entity3.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity3.setStrategy(strategyObj2);
        entity3.setExecutor(executorArr);
        entity3.setSmsExecutor(new JSONArray());
        entity3.setMemo("已经超过一周未拜访，请及时跟进！");

        // TODO 一期砍掉访客计划&短信 2019-12-20
        // ================== 客户生日 =====================
        AiAssistantEntity entity4 = initCustomerForBirthday(corpid, appId, formIds);
        if (Objects.isNull(entity4)) {
            return Arrays.asList(entity1, entity2, entity3);
        }

        return Arrays.asList(entity1, entity2, entity3, entity4);
    }

    private AiAssistantEntity initCustomerForBirthday(String corpid, Long appId, List<Long> formIds) throws XbbException {
        // 获取有客户生日的表单
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("formIdIn", formIds);
        List<PaasFormExplainEntity> explainEntityExtList = paasFormExplainModel.findEntitys(param);
        if (Objects.isNull(explainEntityExtList) || explainEntityExtList.isEmpty()) {
            return null;
        }

        Long formId = null;
        Long menuId = null;
        for (PaasFormExplainEntity entityExt : explainEntityExtList) {
            List<FieldAttrEntity> explainList = JSONObject.parseArray(entityExt.getExplains(), FieldAttrEntity.class);
            for (FieldAttrEntity attrEntity : explainList) {
                if (Objects.equals(CustomerManagementEnum.BIRTHDAY.getAttr(), attrEntity.getAttr()) && Objects.equals(FieldTypeEnum.BIRTHDAY.getType(), attrEntity.getFieldType())) {
                    formId = entityExt.getFormId();
                    menuId = entityExt.getMenuId();
                    break;
                }
            }
        }
        // 无客户生日的表单，直接返回null
        if (Objects.isNull(formId)) {
            return null;
        }
        // 客户生日（前1天）
        ConditionsEntityExt birthdayCondition = new ConditionsEntityExt(CustomerManagementEnum.BIRTHDAY.getAttr(), "",
                CustomerManagementEnum.BIRTHDAY.getFieldType(), SmartSettingsConditionEnum.BEFORE.getSymbol(), Collections.singletonList(1));

        // 执行人（负责人）
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        JSONArray executorArr = new JSONArray();
        executorArr.add(rangeEntity1);

        // 执行策略（09:00，执行1次）
        JSONObject strategyObj = new JSONObject();
        strategyObj.put("strategyNum", 1);
        strategyObj.put("strategyTime", "09:00");
        strategyObj.put("strategyType", 2);
        strategyObj.put("strategyCycle", 1);

        JSONArray triggerCondition = new JSONArray();
        triggerCondition.add(birthdayCondition);
        AiAssistantEntity entity = new AiAssistantEntity();
        entity.setCorpid(corpid);
        entity.setEnable(BasicConstant.NO_USE);
        entity.setName("客户生日");
        entity.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        entity.setAppId(appId);
        entity.setFormId(formId);
        entity.setMenuId(menuId);
        entity.setTriggerCondition(triggerCondition);
        entity.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity.setStrategy(strategyObj);
        entity.setExecutor(executorArr);
        entity.setSmsExecutor(new JSONArray());
        entity.setMemo("客户明天要过生日了，请及时跟进！");
        // ================== 客户生日 =====================

        return entity;
    }

    private List<AiAssistantEntity> initContractSmart(String corpid, Long appId, Long formId, Long menuId) {

        // 触发条件：添加时间、合同到期日期（之前30天）
        ConditionsEntityExt addTimeCondition = new ConditionsEntityExt(ContractEnum.ADD_TIME.getAttr(), "",
                ContractEnum.ADD_TIME.getFieldType(), SmartSettingsConditionEnum.AFTER.getSymbol(), Collections.singletonList(1));

        ConditionsEntityExt deadLineCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.CONTRACT_DEAD_LINE.getAlias(), "",
                SmartSettingsFieldEnum.CONTRACT_DEAD_LINE.getType(), SmartSettingsConditionEnum.BEFORE.getSymbol(), Collections.singletonList(30));

        // 执行策略(每天9:00，执行3次）
        JSONObject strategyObj = new JSONObject();
        strategyObj.put("strategyNum", 3);
        strategyObj.put("strategyTime", "09:00");
        strategyObj.put("strategyType", 2);
        strategyObj.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管，协同人）

        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.COUSERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.COUSERID.getAlias(), BasicConstant.IS_USE);

        // 新增合同：采购员，生产员
        OptionalRangeEntity rangeEntity4 = new OptionalRangeEntity(RoleEnum.PURCHASER.getCode() + "", RoleEnum.PURCHASER.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity5 = new OptionalRangeEntity(RoleEnum.PRODUCTION_WORKER.getCode() + "", RoleEnum.PRODUCTION_WORKER.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);


        // 新增合同
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(addTimeCondition);

        JSONArray executorArr1 = new JSONArray();
        executorArr1.add(rangeEntity1);
        executorArr1.add(rangeEntity2);
        executorArr1.add(rangeEntity3);
        executorArr1.add(rangeEntity4);
        executorArr1.add(rangeEntity5);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("新增合同");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj);
        entity1.setExecutor(executorArr1);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("合同已经创建，请持续关注！");

        // 合同即将到期
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(deadLineCondition);

        JSONArray executorArr2 = new JSONArray();
        executorArr2.add(rangeEntity1);
        executorArr2.add(rangeEntity2);
        executorArr2.add(rangeEntity3);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setName("合同30天到期提醒");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj);
        entity2.setExecutor(executorArr2);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("合同即将到期，请持续关注！");

        return Arrays.asList(entity1, entity2);
    }

    private List<AiAssistantEntity> initPaymentSmart(String corpid, Long appId, Long formId, Long menuId) {


        // 触发条件：预计回款日期（之前3天）、预计回款日期（之后1天）
        ConditionsEntityExt estimateTimeCondition1 = new ConditionsEntityExt(SmartSettingsFieldEnum.PAYMENT_DEAD_LINE.getAlias(), "",
                SmartSettingsFieldEnum.PAYMENT_DEAD_LINE.getType(), SmartSettingsConditionEnum.BEFORE.getSymbol(), Collections.singletonList(3));

        ConditionsEntityExt estimateTimeCondition2 = new ConditionsEntityExt(SmartSettingsFieldEnum.PAYMENT_OVERDUE.getAlias(), "",
                SmartSettingsFieldEnum.PAYMENT_OVERDUE.getType(), SmartSettingsConditionEnum.AFTER.getSymbol(), Collections.singletonList(1));

        // 执行策略(每天9:00，执行3次）
        JSONObject strategyObj1 = new JSONObject();
        strategyObj1.put("strategyNum", 3);
        strategyObj1.put("strategyTime", "09:00");
        strategyObj1.put("strategyType", 2);
        strategyObj1.put("strategyCycle", 1);
        // 执行策略（每周一09:00，执行3次）
//        JSONObject strategyObj2 = new JSONObject();
//        strategyObj2.put("strategyNum", 3);
//        strategyObj2.put("strategyTime", "09:00");
//        strategyObj2.put("strategyType", 3);
//        strategyObj2.put("strategyWeek", 2);
//        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人一级主管，协同人，关联合同负责人）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(), OptionalRangeEnum.DYNAMIC_MANAGER.getValue(),
                FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.COUSERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.COUSERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.LINK_CONTRACT_NAME),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), DynamicManagerConstant.LINK_CONTRACT_ALIAS, BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);
        executorArr.add(rangeEntity3);


        // 回款到期提醒
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(estimateTimeCondition1);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("回款到期前3天提醒");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj1);
        entity1.setExecutor(executorArr);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("回款即将到期，请持续关注！");

        // 回款逾期提醒
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(estimateTimeCondition2);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setName("回款逾期");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj1);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("回款已逾期，请持续关注！");

        return Arrays.asList(entity1, entity2);
    }

    private List<AiAssistantEntity> initOpportunitySmart(String corpid, Long appId, Long formId, Long menuId) {

        // 触发条件：机会阶段、最后跟进时间(大于等于7天）
        // TODO 销售阶段变更（销售阶段等于某阶段）默认场景砍掉 12月18日会议确定
//        ConditionsEntityExt stageCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.OPPORTUNITY_STAGE.getAlias(), "",
//                SmartSettingsFieldEnum.OPPORTUNITY_STAGE.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1));

        ConditionsEntityExt forgetCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.FORGET_OPPORTUNITY.getAlias(), "",
                SmartSettingsFieldEnum.FORGET_OPPORTUNITY.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        // 执行策略(每天9:00，执行3次）
        JSONObject strategyObj1 = new JSONObject();
        strategyObj1.put("strategyNum", 3);
        strategyObj1.put("strategyTime", "09:00");
        strategyObj1.put("strategyType", 2);
        strategyObj1.put("strategyCycle", 1);
        // 执行策略（09:00，执行1次）
        JSONObject strategyObj2 = new JSONObject();
        strategyObj2.put("strategyNum", 1);
        strategyObj2.put("strategyTime", "09:00");
        strategyObj2.put("strategyType", 2);
        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);


        // 销售机会阶段变更提醒
//        JSONArray triggerCondition1 = new JSONArray();
//        triggerCondition1.add(stageCondition);
//
//        AiAssistantEntity entity1 = new AiAssistantEntity();
//        entity1.setCorpid(corpid);
//        entity1.setEnable(BasicConstant.NO_USE);
//        entity1.setName("销售阶段变更提醒");
//        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
//        entity1.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
//        entity1.setAppId(appId);
//        entity1.setFormId(formId);
//        entity1.setTriggerCondition(triggerCondition1);
//        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
//        entity1.setStrategy(strategyObj1);
//        entity1.setExecutor(executorArr);
//        entity1.setSmsExecutor(new JSONArray());
//        entity1.setMemo("{销售机会}阶段变更啦，快去处理吧！");

        // 遗忘销售机会
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(forgetCondition);

        AiAssistantEntity entity2 = new AiAssistantEntity();
//        BeanUtil.copyProperties(entity1, entity2);
        entity2.setCorpid(corpid);
        entity2.setEnable(BasicConstant.NO_USE);
        entity2.setName("7天未跟进销售机会提醒");
        entity2.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity2.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
        entity2.setAppId(appId);
        entity2.setFormId(formId);
        entity2.setMenuId(menuId);
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity2.setStrategy(strategyObj2);
        entity2.setExecutor(executorArr);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("已经超过一周未拜访，请及时跟进！");

        return Arrays.asList(entity2);
    }

    private List<AiAssistantEntity> initWorkReportSmart(String corpid, Long appId, Long formId, Long menuId) {
        // 周报提醒
        JSONArray triggerCondition = new JSONArray();
        // 触发条件：无（为区分是日报/周报/月报，设置到触发条件里）
        ConditionsEntityExt condition = new ConditionsEntityExt();
        condition.setFieldType(WorkReportTypeEnum.WEEKLY.getType());

        // 执行策略（每周五15:00，执行1次）
        JSONObject strategyObj = new JSONObject();
        strategyObj.put("strategyNum", 1);
        strategyObj.put("strategyTime", "15:00");
        strategyObj.put("strategyType", 3);
        strategyObj.put("strategyWeek", 6);
        strategyObj.put("strategyCycle", 1);

        // 执行人（销售）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity = new OptionalRangeEntity(RoleEnum.SALE.getCode() + "", RoleEnum.SALE.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);
        executorArr.add(rangeEntity);

        // 周报提醒
        triggerCondition.add(condition);

        AiAssistantEntity entity = new AiAssistantEntity();
        entity.setCorpid(corpid);
        entity.setEnable(BasicConstant.NO_USE);
        entity.setName("周报提醒");
        entity.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity.setBusinessType(XbbRefTypeEnum.WORK_REPORT.getCode());
        entity.setAppId(appId);
        entity.setFormId(formId);
        entity.setMenuId(menuId);
        entity.setTriggerCondition(triggerCondition);
        entity.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity.setStrategy(strategyObj);
        entity.setExecutor(executorArr);
        entity.setSmsExecutor(new JSONArray());
        entity.setMemo("请在周五下班前提交本周工作总结！");

        return Collections.singletonList(entity);
    }

    private List<AiAssistantEntity> initSupplierSmart(String corpid, Long appId, Long formId, Long menuId) {
        // 新增供应商、无跟进供应商、遗忘供应商

        // 触发条件：添加时间、未跟进时间、最后跟进时间(大于等于7天）
        ConditionsEntityExt addTimeCondition = new ConditionsEntityExt(SupplierEnum.ADD_TIME.getAttr(), "",
                SupplierEnum.ADD_TIME.getFieldType(), SmartSettingsConditionEnum.AFTER.getSymbol(), Collections.singletonList(1));

        ConditionsEntityExt noConnectCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.NO_CONNECT_SUPPLIER.getAlias(), "",
                SmartSettingsFieldEnum.NO_CONNECT_SUPPLIER.getType(), SmartSettingsConditionEnum.EQUAL_CONDITION.getSymbol(), new ArrayList<>());

        ConditionsEntityExt forgetCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.FORGET_SUPPLIER.getAlias(), "",
                SmartSettingsFieldEnum.FORGET_SUPPLIER.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        // 执行策略(每天9:00，执行3次）
        JSONObject strategyObj1 = new JSONObject();
        strategyObj1.put("strategyNum", 3);
        strategyObj1.put("strategyTime", "09:00");
        strategyObj1.put("strategyType", 2);
        strategyObj1.put("strategyCycle", 1);
        // 执行策略（09:00，执行1次）
        JSONObject strategyObj2 = new JSONObject();
        strategyObj2.put("strategyNum", 1);
        strategyObj2.put("strategyTime", "09:00");
        strategyObj2.put("strategyType", 2);
        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);


        // 新增供应商
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(addTimeCondition);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("新增供应商");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj1);
        entity1.setExecutor(executorArr);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("新增的供应商，请及时跟进！");

        // 无跟进供应商
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(noConnectCondition);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setName("无跟进供应商");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj2);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("还没有跟进记录，请及时跟进！");

        // 遗忘供应商
        JSONArray triggerCondition3 = new JSONArray();
        triggerCondition3.add(forgetCondition);

        AiAssistantEntity entity3 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity3);
        entity3.setName("7天未跟进供应商提醒");
        entity3.setTriggerCondition(triggerCondition3);
        entity3.setStrategy(strategyObj2);
        entity3.setSmsExecutor(new JSONArray());
        entity3.setMemo("已经超过一周未拜访，请跟进！");

        return Arrays.asList(entity1, entity2, entity3);
    }

    private List<AiAssistantEntity> initPurchaseSmart(String corpid, Long appId, Long formId, Long menuId) {

        // 触发条件：添加时间、预计到货时间(之前2天）、待入库（大于等于7天）
        ConditionsEntityExt addTimeCondition = new ConditionsEntityExt(PurchaseEnum.ADD_TIME.getAttr(), "",
                PurchaseEnum.ADD_TIME.getFieldType(), SmartSettingsConditionEnum.AFTER.getSymbol(), Collections.singletonList(1));

        ConditionsEntityExt arriveTimeCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.PURCHASE_ARRIVE_TIME.getAlias(), "",
                SmartSettingsFieldEnum.PURCHASE_ARRIVE_TIME.getType(), SmartSettingsConditionEnum.BEFORE.getSymbol(), Collections.singletonList(2));
        ConditionsEntityExt waitInstockCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.WAIT_INSTOCK.getAlias(), "",
                SmartSettingsFieldEnum.WAIT_INSTOCK.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        // 执行策略(每天9:00，执行2次）
        JSONObject strategyObj1 = new JSONObject();
        strategyObj1.put("strategyNum", 2);
        strategyObj1.put("strategyTime", "09:00");
        strategyObj1.put("strategyType", 2);
        strategyObj1.put("strategyCycle", 1);
        // 执行策略（09:00，执行1次）
        JSONObject strategyObj2 = new JSONObject();
        strategyObj2.put("strategyNum", 1);
        strategyObj2.put("strategyTime", "09:00");
        strategyObj2.put("strategyType", 2);
        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管，关联仓库负责人）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
//        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "",
//                DynamicManagerConstant.LINK_WARE_HOUSE_NAME, OptionalRangeEnum.DYNAMIC_MANAGER.getValue(),
//                DynamicManagerConstant.LINK_WARE_HOUSE_ALIAS, BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);
//        executorArr.add(rangeEntity3);


        // 新增采购合同
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(addTimeCondition);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("新增采购合同");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj2);
        entity1.setExecutor(executorArr);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("采购合同已经创建，请持续关注！");

        // 采购到货提醒
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(arriveTimeCondition);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setName("采购2天后到货提醒");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj1);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("采购合同即将到货，请持续关注！");

        // 待入库提醒
        JSONArray triggerCondition3 = new JSONArray();
        triggerCondition3.add(waitInstockCondition);

        AiAssistantEntity entity3 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity3);
        entity3.setName("待入库7天未处理提醒");
        entity3.setTriggerCondition(triggerCondition3);
        entity3.setStrategy(strategyObj2);
        entity3.setSmsExecutor(new JSONArray());
        entity3.setMemo("待入库单超期未处理！");

        return Arrays.asList(entity1, entity2, entity3);
    }

    private List<AiAssistantEntity> initPayPlanSmart(String corpid, Long appId, Long formId, Long menuId) {

        // 触发条件：预计付款时间（之前3天）、预计付款时间（之后1天）
        ConditionsEntityExt estimateTimeCondition1 = new ConditionsEntityExt(SmartSettingsFieldEnum.PAY_PLAN_DEAD_LINE.getAlias(), "",
                SmartSettingsFieldEnum.PAY_PLAN_DEAD_LINE.getType(), SmartSettingsConditionEnum.BEFORE.getSymbol(), Collections.singletonList(3));

        ConditionsEntityExt estimateTimeCondition2 = new ConditionsEntityExt(SmartSettingsFieldEnum.PAY_PLAN_OVERDUE.getAlias(), "",
                SmartSettingsFieldEnum.PAY_PLAN_OVERDUE.getType(), SmartSettingsConditionEnum.AFTER.getSymbol(), Collections.singletonList(1));

        // 执行策略(每天9:00，执行3次）
        JSONObject strategyObj1 = new JSONObject();
        strategyObj1.put("strategyNum", 3);
        strategyObj1.put("strategyTime", "09:00");
        strategyObj1.put("strategyType", 2);
        strategyObj1.put("strategyCycle", 1);
//        // 执行策略（每周一9:00，执行4次）
//        JSONObject strategyObj2 = new JSONObject();
//        strategyObj2.put("strategyNum", 4);
//        strategyObj2.put("strategyTime", "09:00");
//        strategyObj2.put("strategyType", 3);
//        strategyObj2.put("strategyWeek", 2);
//        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管），财务
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(RoleEnum.TREASURER.getCode() + "", RoleEnum.TREASURER.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);
        executorArr.add(rangeEntity3);


        // 付款到期提醒
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(estimateTimeCondition1);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("付款到期前3天提醒");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj1);
        entity1.setExecutor(executorArr);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("付款即将到期，请持续关注！");

        // 付款逾期提醒
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(estimateTimeCondition2);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setName("付款逾期");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj1);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("付款已逾期，请持续关注！");

        return Arrays.asList(entity1, entity2);
    }

    private List<AiAssistantEntity> initProductionOrderSmart(String corpid, Long appId, Long formId, Long menuId) {

        JSONArray triggerCondition = new JSONArray();
        // 触发条件：计划完成时间（之前2天）
        ConditionsEntityExt stageCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.PRODUCTION_ORDER_PLAN_TIME.getAlias(), "",
                SmartSettingsFieldEnum.PRODUCTION_ORDER_PLAN_TIME.getType(), SmartSettingsConditionEnum.BEFORE.getSymbol(), Collections.singletonList(2));


        // 执行策略(每天9:00，执行2次）
        JSONObject strategyObj = new JSONObject();
        strategyObj.put("strategyNum", 2);
        strategyObj.put("strategyTime", "09:00");
        strategyObj.put("strategyType", 2);
        strategyObj.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管，关联仓库负责人）
        JSONArray executorArr = new JSONArray();
        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
//        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "",
//                DynamicManagerConstant.LINK_WARE_HOUSE_NAME, OptionalRangeEnum.DYNAMIC_MANAGER.getValue(),
//                DynamicManagerConstant.LINK_WARE_HOUSE_ALIAS, BasicConstant.IS_USE);
        executorArr.add(rangeEntity1);
        executorArr.add(rangeEntity2);
//        executorArr.add(rangeEntity3);


        // 生产完成提醒
        triggerCondition.add(stageCondition);

        AiAssistantEntity entity = new AiAssistantEntity();
        entity.setCorpid(corpid);
        entity.setEnable(BasicConstant.NO_USE);
        entity.setName("生产完成前2天提醒");
        entity.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity.setBusinessType(XbbRefTypeEnum.PRODUCTION_ORDER.getCode());
        entity.setAppId(appId);
        entity.setFormId(formId);
        entity.setMenuId(menuId);
        entity.setTriggerCondition(triggerCondition);
        entity.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity.setStrategy(strategyObj);
        entity.setExecutor(executorArr);
        entity.setSmsExecutor(new JSONArray());
        entity.setMemo("产品生产完成啦，快去入库吧！");

        return Collections.singletonList(entity);
    }

    private List<AiAssistantEntity> initLinkContractSmart(String corpid, Long appId, Long formId, Long menuId) {


        // 触发条件：待采购（大于等于7天）、待生产(大于等于7天）、待出库（大于等于7天）
        ConditionsEntityExt waitPurchaseCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.WAIT_PURCHASE.getAlias(), "",
                SmartSettingsFieldEnum.WAIT_PURCHASE.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        ConditionsEntityExt waitProductionCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getAlias(), "",
                SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        ConditionsEntityExt waitOutstockCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.WAIT_OUTSTOCK.getAlias(), "",
                SmartSettingsFieldEnum.WAIT_OUTSTOCK.getType(), ConditionEnum.GREATEREQUAL.getSymbol(), Collections.singletonList(7));

        // 执行策略（09:00，执行1次）
        JSONObject strategyObj2 = new JSONObject();
        strategyObj2.put("strategyNum", 1);
        strategyObj2.put("strategyTime", "09:00");
        strategyObj2.put("strategyType", 2);
        strategyObj2.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管，关联仓库负责人）

        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
//        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", DynamicManagerConstant.LINK_WARE_HOUSE_NAME,
//                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), DynamicManagerConstant.LINK_WARE_HOUSE_ALIAS, BasicConstant.IS_USE);
        // 采购员、生产员
        OptionalRangeEntity rangeEntity4 = new OptionalRangeEntity(RoleEnum.PURCHASER.getCode() + "", RoleEnum.PURCHASER.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity5 = new OptionalRangeEntity(RoleEnum.PRODUCTION_WORKER.getCode() + "", RoleEnum.PRODUCTION_WORKER.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);


        // 待采购提醒
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(waitPurchaseCondition);

        JSONArray executorArr1 = new JSONArray();
        executorArr1.add(rangeEntity1);
        executorArr1.add(rangeEntity2);
        executorArr1.add(rangeEntity4);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("待采购7天未处理提醒");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj2);
        entity1.setExecutor(executorArr1);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("待采购单超期未处理！");

        // 待生产提醒
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(waitProductionCondition);

        JSONArray executorArr2 = new JSONArray();
        executorArr2.add(rangeEntity1);
        executorArr2.add(rangeEntity2);
        executorArr2.add(rangeEntity5);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setEnable(BasicConstant.NO_USE);
        entity2.setName("待生产7天未处理提醒");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj2);
        entity2.setExecutor(executorArr2);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("待生产单超期未处理！");

        // 待出库提醒
        JSONArray triggerCondition3 = new JSONArray();
        triggerCondition3.add(waitOutstockCondition);

        JSONArray executorArr3 = new JSONArray();
        executorArr3.add(rangeEntity1);
        executorArr3.add(rangeEntity2);
//        executorArr3.add(rangeEntity3);

        AiAssistantEntity entity3 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity3);
        entity3.setEnable(BasicConstant.NO_USE);
        entity3.setName("待出库7天未处理提醒");
        entity3.setTriggerCondition(triggerCondition3);
        entity3.setStrategy(strategyObj2);
        entity3.setExecutor(executorArr3);
        entity3.setSmsExecutor(new JSONArray());
        entity3.setMemo("待出库单超期未处理！");

        return Arrays.asList(entity1, entity2, entity3);
    }

    private List<AiAssistantEntity> initProductSmart(String corpid, Long appId, Long formId, Long menuId) {

        // 触发条件：库存预警下限、库存预警上限、产品临期
        ConditionsEntityExt stockLowerCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getAlias(), "",
                SmartSettingsFieldEnum.PRODUCT_STOCK_LOWER_WARNING.getType(), SmartSettingsConditionEnum.EQUAL_CONDITION.getSymbol(), new ArrayList<>());

        ConditionsEntityExt stockUpperCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getAlias(), "",
                SmartSettingsFieldEnum.PRODUCT_STOCK_UPPER_WARNING.getType(), SmartSettingsConditionEnum.EQUAL_CONDITION.getSymbol(), new ArrayList<>());
        // 产品过期日期（1～15）
        List<Object> expireTimeRange = Arrays.asList(1,15);
        ConditionsEntityExt expireCondition = new ConditionsEntityExt(SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getAlias(), "",
                SmartSettingsFieldEnum.PRODUCT_EXPIRE_WARNING.getType(), ConditionEnum.RANGE.getSymbol(), expireTimeRange);

        // 执行策略（09:00，执行1次）
        JSONObject strategyObj = new JSONObject();
        strategyObj.put("strategyNum", 1);
        strategyObj.put("strategyTime", "09:00");
        strategyObj.put("strategyType", 2);
        strategyObj.put("strategyCycle", 1);

        // 执行人（负责人，负责人一级主管，关联仓库负责人），采购员

        OptionalRangeEntity rangeEntity1 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity2 = new OptionalRangeEntity(DynamicManagerLevelEnum.ONE_LEVEL.getLevel() + "",
                I18nMessageUtil.getMessage(DynamicManagerConstant.OWNERID) + DynamicManagerLevelEnum.ONE_LEVEL.getName(),
                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), FieldTypeEnum.OWNERID.getAlias(), BasicConstant.IS_USE);
//        OptionalRangeEntity rangeEntity3 = new OptionalRangeEntity(DynamicManagerLevelEnum.ZERO_LEVEL.getLevel() + "", DynamicManagerConstant.LINK_WARE_HOUSE_NAME,
//                OptionalRangeEnum.DYNAMIC_MANAGER.getValue(), DynamicManagerConstant.LINK_WARE_HOUSE_ALIAS, BasicConstant.IS_USE);
        OptionalRangeEntity rangeEntity4 = new OptionalRangeEntity(RoleEnum.PURCHASER.getCode() + "", RoleEnum.PURCHASER.getName(),
                OptionalRangeEnum.ROLE.getValue(), null, BasicConstant.IS_USE);


        // 产品库存下限预警
        JSONArray triggerCondition1 = new JSONArray();
        triggerCondition1.add(stockLowerCondition);

        JSONArray executorArr1 = new JSONArray();
        executorArr1.add(rangeEntity1);
        executorArr1.add(rangeEntity2);
//        executorArr1.add(rangeEntity3);
        executorArr1.add(rangeEntity4);

        AiAssistantEntity entity1 = new AiAssistantEntity();
        entity1.setCorpid(corpid);
        entity1.setEnable(BasicConstant.NO_USE);
        entity1.setName("产品库存下限预警");
        entity1.setSaasMark(SaasMarkEnum.SAAS.getCode());
        entity1.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        entity1.setAppId(appId);
        entity1.setFormId(formId);
        entity1.setMenuId(menuId);
        entity1.setTriggerCondition(triggerCondition1);
        entity1.setAction(SmartActionTypeEnum.MESSAGE.getCode());
        entity1.setStrategy(strategyObj);
        entity1.setExecutor(executorArr1);
        entity1.setSmsExecutor(new JSONArray());
        entity1.setMemo("已到达库存预警下限，快去处理吧！");

        // 产品库存上限预警
        JSONArray triggerCondition2 = new JSONArray();
        triggerCondition2.add(stockUpperCondition);

        AiAssistantEntity entity2 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity2);
        entity2.setName("产品库存上限预警");
        entity2.setTriggerCondition(triggerCondition2);
        entity2.setStrategy(strategyObj);
        entity2.setSmsExecutor(new JSONArray());
        entity2.setMemo("已到达库存预警上限，快去处理吧！");

        // 产品保质期预警
        JSONArray triggerCondition3 = new JSONArray();
        triggerCondition3.add(expireCondition);

        JSONArray executorArr3 = new JSONArray();
        executorArr3.add(rangeEntity1);
        executorArr3.add(rangeEntity2);
//        executorArr3.add(rangeEntity3);

        AiAssistantEntity entity3 = new AiAssistantEntity();
        BeanUtil.copyProperties(entity1, entity3);
        entity3.setName("产品过期前1～15天提醒");
        entity3.setTriggerCondition(triggerCondition3);
        entity3.setStrategy(strategyObj);
        entity3.setExecutor(executorArr3);
        entity3.setSmsExecutor(new JSONArray());
        entity3.setMemo("还有15天过期，快去处理吧！");

        return Arrays.asList(entity1, entity2, entity3);
    }
}
